您好,登錄后才能下訂單哦!
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 讀文件案例 { class Program { static void Main(string[] args) { Console.WriteLine("請輸入文件名"); string fileName = Console.ReadLine();//獲得用戶輸入 File file = Factory.GetFileName(fileName); file.OpenFile(); Console.ReadKey(); } } /// <summary> /// 父類,等待子類實現 /// </summary> public abstract class File { private string _fileName;//文件名 public string FileName { get { return _fileName; } set { _fileName = value; } } private string _extension;//后綴名 public string Extension { get { return _extension; } set { _extension = value; } } /// <summary> /// 構造函數 /// </summary> /// <param name="fileName"></param> public File(string fileName) { //在本類中,用私有字段即可,不必要使用屬性來保護對應的字段 this._fileName = Path.GetFileNameWithoutExtension(fileName); this._extension = Path.GetExtension(fileName); } public abstract void OpenFile(); } public class TxtFile : File { /// <summary> /// 子類構造函數,調用父類構造函數為字段賦值 /// </summary> /// <param name="fileName"></param> public TxtFile(string fileName) : base(fileName) { } public override void OpenFile() { //此時就需要用屬性來保護字段了 Console.WriteLine("文件名為{0},后綴名為{1}", this.FileName, this.Extension); } } public class AviFile : File { public AviFile(string fileName) : base(fileName) { } public override void OpenFile() { Console.WriteLine("文件名為{0},后綴名為{1}", this.FileName, this.Extension); } } public class Factory { public static File GetFileName(string fileName) { File file = null; switch (Path.GetExtension(fileName).ToLower()) { case "txt": case ".txt": file = new TxtFile(fileName); break; case "avi": case ".avi": file = new AviFile(fileName); break; //父類是虛方法的寫法 //case "txt": //case ".txt": return new TxtFile(fileName); //default: return new File(fileName); } return file; } } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。