.NET 经典案例

1、模拟磁盘打开文件(面向对象继承)

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

namespace 模拟磁盘打开文件
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请选择要进入的磁盘");
            string path = Console.ReadLine();
            Console.WriteLine("请选择要进入的文件");
            string fileName = Console.ReadLine();
            //文件的全路径:path+fileName
            FileFather ff = GetFile(fileName, path + fileName);
            ff.OpenFile();
            Console.ReadKey();
        }

        public static FileFather GetFile(string fileName, string fullPath)
        {
            string extension = Path.GetExtension(fileName);
            FileFather ff = null;
            switch (extension)
            {
                case ".txt": ff = new TxtPath(fullPath);
                    break;
                case ".jpg": ff = new JpgPath(fullPath);
                    break;
                case ".wav": ff = new WavPath(fullPath);
                    break;
            }

            return ff;
        }
    }

    public abstract class FileFather
    {
        //文件名
        public string FileName
        {
            get;
            set;
        }
        //定义一个构造函数,获取文件全路径
        public FileFather(string fileName)
        {
            this.FileName = fileName;
        }
        //打开文件的抽象方法
        public abstract void OpenFile();
    }

    public class TxtPath : FileFather
    {
        //子类调用父类的构造函数,使用关键字base
        public TxtPath(string fullPath)
            : base(fullPath)
        {

        }

        public override void OpenFile()
        {
            ProcessStartInfo psi = new ProcessStartInfo(this.FileName);
            Process p = new Process();
            p.StartInfo = psi;
            p.Start();
        }
    }

    public class JpgPath : FileFather
    {
        public JpgPath(string fullPath)
            : base(fullPath)
        {

        }

        public override void OpenFile()
        {
            ProcessStartInfo psi = new ProcessStartInfo(this.FileName);
            Process p = new Process();
            p.StartInfo = psi;
            p.Start();
        }
    }

    public class WavPath : FileFather
    {
        public WavPath(string fullPath)
            : base(fullPath)
        {

        }

        public override void OpenFile()
        {
            ProcessStartInfo psi = new ProcessStartInfo(this.FileName);
            Process p = new Process();
            p.StartInfo = psi;
            p.Start();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/songhe123/p/9713371.html