进程(应用程序)之二

来源:互联网 发布:淘宝app购买记录怎么查 编辑:程序博客网 时间:2024/04/29 15:01

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Console用进程打开文件2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入要打开文件的路径");
            string filePath = Console.ReadLine();
            Console.WriteLine("请输入要打开文件的名称");
            string fileName = Console.ReadLine();
          
            //通过简单工厂设计模式返回父类,因为有时候我们不知道文件是什么名字或格式,所以返回父类。我们是根据子类返回父类,而子类装着对象,所以我们需要根据文件的后缀名来创建子类对象
            BaseFile bf = GetFile(filePath,fileName);//声明父类,用来接收返回
            if (bf != null)//如果是null,要抛异常
            {
                bf.OpenFile();
            }
            Console.ReadKey();
        }
        static BaseFile GetFile(string filePath,string fileName)
        {
            BaseFile bf=null;//声明父类,因为要返回父类
            string strExtension = Path.GetExtension(fileName);//获取文件后缀名
            switch (strExtension)
            {
                case".txt":
                    bf = new TxtFile(filePath, fileName);
                    break;
                case".mp4":
                    bf = new Mp4File(filePath, fileName);
                    break;
            }
            return bf;
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Console用进程打开文件2
{
    class BaseFile
    {
        //类包括字段(用来存储数据)、属性(用来保护字段,属性的本质是两个函数get和set)、构造函数(用来初始化对象,给对象的每一个属性赋值)、函数(描述对象的行为)、索引器(以索引的方式去访问对象)
        private string _filePath;//如果不加private,字段的默认访问权限也是类的内部私有的
       
        public string FilePath//封装属性,快捷键Ctrl+R+E
        {
            get { return _filePath; }
            set { _filePath = value; }
        }
        public string FileName { get; set; }//自动属性,prop+两下tab键,其作用跟封装属性是一样的
      
        public BaseFile(string filePath, string fileName)//构造函数,已经有参数了
        {
            this.FilePath = filePath;
            this.FileName = fileName;
        }
        //设计一个函数,用来打开指定的文件
        public void OpenFile()
        {
            ProcessStartInfo psi = new ProcessStartInfo(this.FilePath+"\\"+this.FileName);
            Process pro=new Process();
            pro.StartInfo = psi;
            pro.Start();
        }
    }
    class TxtFile : BaseFile
    {
        //因为子类会默认调用父类无参数的构造函数,如果没有下面这行代码,生成解决方案的时候会报错:父类中没有0个参数的构造函数
        public TxtFile(string filePath, string fileName)
            : base(filePath, fileName)//:base显示的是在子类中去调用父类的构造函数,将子类的参数filePath传递给父类的filePath,而:this显示调用当前自己的构造函数
        { }
    }

    class Mp4File : BaseFile
    {
        public Mp4File(string filePath, string fileName)
            : base(filePath, fileName)
        { }
    }
}

 

0 0
原创粉丝点击