>  기사  >  백엔드 개발  >  C# 기본 지식 편집: 기본 지식(6) 추상 클래스 및 추상 메서드

C# 기본 지식 편집: 기본 지식(6) 추상 클래스 및 추상 메서드

黄舟
黄舟원래의
2017-02-11 13:14:301221검색

실제 프로젝트에서 상위 클래스를 디자인할 때 클래스가 구체적인 실행 프로세스를 결정할 수 없는 경우가 종종 있습니다. 예를 들어,

  public class AFile
    {
        private string name = string.Empty;

        private string path = string.Empty;

        private FileType type = FileType.IsUnknown;

        public string Name
        {
            get 
            { 
                return name;
            }
        }

        public string Path
        {
            get 
            { 
                return path; 
            }
        }

        public FileType Type
        {
            get { return type; }
        }

        public AFile(string name, string path, FileType type)
        {
            this.name = name;

            this.path = path;

            this.type = type;
        }

        public void Copy(string destPath)
        {
            //不知道怎么写,因为可能是文件还可能是文件夹,如果是压缩的还要解压
        }
    }

    public enum FileType
    {
        IsUnknown = 0,//类型不明

        IsFile = 1,//文件

        IsDirectory =2,//文件夹

        IsCompression//压缩的
    }

라는 파일 클래스를 디자인합니다. 이것은 상위 클래스이며 복사 방법을 어떻게 작성해야 합니까? 파일은 네 가지 상태로 존재하고 필요에 따라 나중에 추가될 수 있으므로 파일 형식에 따라 복사 방법이 다르며 프로젝트 요구에 따라 특정 파일에 대해 일부 특수 처리가 수행될 수 있습니다. 이런 방식으로 이 상위 클래스를 다시 디자인할 때 복사 메서드에 대한 코드를 작성할 수 없습니다. 이를 상속받은 사람만 이 메서드를 재정의하고 필요에 따라 다른 실행 코드를 작성할 수 있습니다.
이처럼 클래스에는 특정 메서드가 있지만 해당 메서드에는 특정 실행 프로세스가 없습니다. 이러한 메서드를 "추상 메서드"라고 합니다.
위 AFile 클래스의 Copy 메소드를 추상 메소드라고 하는데 문제가 있습니다. AFile 클래스를 인스턴스화하면 Copy 메소드가 이 객체의 동작이 되겠지만 실제로 Copy 메소드는 확실하지 않습니다. 아직. 이는 사물의 객관적인 법칙과 일치하지 않습니다. 따라서 이 클래스는 인스턴스화할 수 없습니다. 즉, 클래스에 추상 메서드가 있으면 이 클래스를 인스턴스화할 수 없습니다. 이러한 클래스를 "추상 클래스"라고 합니다. Abstract는 인스턴스화할 수 없지만 여전히 클래스입니다. 추상 클래스와 추상 메서드는 abstract 키워드로 수정됩니다.
보시다시피 추상 클래스에는 추상 메서드와 비추상 메서드라는 두 가지 메서드가 있습니다.
비추상 메서드, 추상 클래스가 상속되고 하위 클래스에는 직접 사용하거나 재정의할 수 있는 비추상 메서드가 있습니다.
추상 클래스는 재정의하고 다시 작성해야 합니다.
위 파일 클래스 수정:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace YYS.CSharpStudy.MainConsole
{
    public abstract class AFile
    {
        private string name = string.Empty;

        private string path = string.Empty;

        private FileType type = FileType.IsUnknown;

        public string Name
        {
            get 
            { 
                return name;
            }
        }

        public string AFilePath
        {
            get 
            { 
                return path; 
            }
        }

        public FileType Type
        {
            get { return type; }
        }

        public AFile(string name, string path, FileType type)
        {
            this.name = name;

            this.path = path;

            this.type = type;
        }

        public abstract void Copy(string destPath);
    }

    public enum FileType
    {
        IsUnknown = 0,//类型不明

        IsFile = 1,//文件

        IsDirectory =2,//文件夹

        IsCompression//压缩的
    }

    /// <summary>
    /// 文件类
    /// </summary>
    public class FileInfo : AFile
    {
        public FileInfo(string name, string path, FileType type)

            : base(name, path, type)
        {

        }

        /// <summary>
        /// 文件的拷贝方法
        /// </summary>
        public override void Copy(string destPath)
        {
            if (string.IsNullOrEmpty(destPath))
            {
                string sourcePath = this.AFilePath + this.Name;
                //此时name是文件名,带有后缀名,加起来是文件路径
                destPath += this.Name;

                if (File.Exists(sourcePath))
                {
                    File.Copy(sourcePath, destPath, true);
                }
            }
        }
    }

    /// <summary>
    /// 文件夹类
    /// </summary>
    public class FileDirectoryInfo : AFile
    {
        public FileDirectoryInfo(string name, string path, FileType type)

            : base(name, path, type)
        {

        }

        /// <summary>
        /// 文件的拷贝方法
        /// </summary>
        public override void Copy(string destPath)
        {
            if (string.IsNullOrEmpty(destPath))
            {
                string sourcePath = this.AFilePath + this.Name;
                //此时文件名是文件夹名,加起来是文件夹路径
                destPath += this.Name;

                if (Directory.Exists(sourcePath))
                {
                    CopyDirectory(sourcePath, destPath);
                }
            }
        }
        /// <summary>
        /// 拷贝文件夹的方法
        /// </summary>
        private void CopyDirectory(string sourcePath, string destPath)
        {
            try
            {
                if (!Directory.Exists(destPath))
                {
                    Directory.CreateDirectory(destPath);
                }

                DirectoryInfo directoryInfo = new DirectoryInfo(sourcePath);

                foreach (FileSystemInfo fileInfo in directoryInfo.GetFileSystemInfos())
                {
                    string subFileOrDirectoryName = Path.Combine(destPath, fileInfo.Name);

                    if (fileInfo is DirectoryInfo)
                    {
                        this.CopyDirectory(fileInfo.FullName, subFileOrDirectoryName);
                    }
                    else
                    {
                        if (File.Exists(sourcePath))
                        {
                            File.Copy(sourcePath, destPath, true);
                        }
                    }
                }
            }
            catch{}
        }
    }

}

이렇게 하면 추상 클래스 상속 및 구현이 완료됩니다. 그러나 하위 클래스가 추상 클래스를 상속하지만 추상 메서드를 구현하지 않는 경우 하위 클래스도 추상 클래스로 존재합니다. 추상 메서드가 있는 클래스를 추상 클래스라고 합니다. 어떤 경우에는 추상 메서드가 없는 클래스도 추상 키워드를 사용하여 추상 클래스로 정의할 수 있습니다. 이는 클래스를 추상화할 수 없고 상속해야 함을 나타냅니다.

위는 C# 기본 지식 요약입니다: 기본 지식 (6) 추상 클래스 및 추상 메서드에 대한 자세한 내용은 PHP 중국어 사이트(www.php.cn)를 참고하세요. !


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.