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(); } } ////// 父類,等待子類實現(xiàn) /// 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; } } ////// 構(gòu)造函數(shù) /// /// public File(string fileName) { //在本類中,用私有字段即可,不必要使用屬性來保護對應的字段 this._fileName = Path.GetFileNameWithoutExtension(fileName); this._extension = Path.GetExtension(fileName); } public abstract void OpenFile(); } public class TxtFile : File { ////// 子類構(gòu)造函數(shù),調(diào)用父類構(gòu)造函數(shù)為字段賦值 /// /// 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; } } }
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務器,動態(tài)BGP最優(yōu)骨干路由自動選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡助力業(yè)務部署。公司持有工信部辦法的idc、isp許可證, 機房獨有T級流量清洗系統(tǒng)配攻擊溯源,準確進行流量調(diào)度,確保服務器高可用性。佳節(jié)活動現(xiàn)已開啟,新人活動云服務器買多久送多久。