您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。