扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
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(); } } ////// 父类,等待子类实现 /// 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; } } ////// 构造函数 /// /// public File(string fileName) { //在本类中,用私有字段即可,不必要使用属性来保护对应的字段 this._fileName = Path.GetFileNameWithoutExtension(fileName); this._extension = Path.GetExtension(fileName); } public abstract void OpenFile(); } public class TxtFile : File { ////// 子类构造函数,调用父类构造函数为字段赋值 /// /// 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; } } }
创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流