C# 기본 지식 정리: 기본 지식(7) 메서드 숨기기

黄舟
풀어 주다: 2017-02-11 13:15:32
원래의
1139명이 탐색했습니다.

상속 및 추상 클래스에서 언급했듯이 하위 클래스와 상위 클래스의 메서드 사이에는 다음과 같은 관계가 있습니다.
하위 클래스는 상위 클래스 메서드를 직접 사용합니다(그러나 상위 클래스 메서드는 공개 또는 보호 유형이어야 합니다).
하위 클래스의 메서드가 상위 클래스의 메서드를 재정의합니다(재정의).
하위 클래스의 메서드가 상위 클래스의 메서드를 재정의합니다(오버로드).
다음 상황을 살펴보세요.

    public class YSchool
    {
        private int id = 0;

        private string name = string.Empty;

        public int ID
        {
            get
            {
                return this.id;
            }
        }

        public string Name
        {
            get
            {
                return name;
            }
        }

        public YSchool()
        {
            this.id = 0;

            this.name = @"清华大学附中";
        }

        public  YSchool(int id, string name)
        {
            this.id = id;

            this.name = name;
        }

        /// <summary>
        /// 构造器
        /// </summary>
        public  YSchool(int id)
        {
            this.id = id;

            this.name = @"陕师大附中";
        }
    }

    public class YTeacher
    {
        private int id = 0;

        private string name = string.Empty;

        private YSchool school = null;

        private string introDuction = string.Empty;

        private string imagePath = string.Empty;

        public int ID
        {
            get
            {
                return id;
            }
        }

        public string Name
        {
            get
            {
                return name;
            }
        }

        public YSchool School
        {
            get
            {
                if (school == null)
                {
                    school = new YSchool();
                }
                return school;
            }

            set
            {
                school = value;
            }
        }

        public string IntroDuction
        {
            get
            {
                return introDuction;
            }

            set
            {
                introDuction = value;
            }
        }

        public string ImagePath
        {
            get
            {
                return imagePath;
            }

            set
            {
                imagePath = value;
            }
        }
        /// <summary>
        /// 构造器
        /// </summary>
        public YTeacher(int id, string name)
        {
            this.id = id;

            this.name = name;
        }

        /// <summary>
        /// 构造器
        /// </summary>
        public YTeacher(int id, string name, YSchool school)
        {
            this.id = id;

            this.name = name;

            this.school = school;
        }

        /// <summary>
        /// 给学生讲课的方法
        /// </summary>
        public void ToTeachStudents()
        {
            Console.WriteLine(string.Format(@"{0} 老师教育同学们: Good Good Study,Day Day Up!", this.Name));
        }
        /// <summary>
        /// 惩罚犯错误学生的方法
        /// 加virtual关键字,表示该方法可以被覆盖重写
        /// </summary>
        /// <param name="punishmentContent"></param>
        public virtual void PunishmentStudents(string punishmentContent)
        {
            Console.WriteLine(string.Format(@"{0} 的{1} 老师让犯错误的学生 {2}。", this.School.Name, this.name, punishmentContent));
        }
    }

    public class UniversityTeacher : YTeacher
    {
        public UniversityTeacher(int id, string name,YSchool school)

            : base(id, name, school)
        {

        }

        /// <summary>
        /// 隐藏父类的同名方法,隐藏后该类只能访问隐藏后的方法,不能访问到父类的该方法了。
        /// </summary>
        public new void ToTeachStudents()
        {
            Console.WriteLine(string.Format(@"{0} 老师教育同学们:认真学习.net!", this.Name));
        }
        
        /// <summary>
        /// 覆盖
        /// </summary>
        public override void PunishmentStudents(string punishmentContent)
        {
            base.PunishmentStudents(punishmentContent);//也可以不执行父类方法。

            //自己的代码
        }
    }
로그인 후 복사
rrree

결과:

new를 사용하여 상위 클래스 메서드와 이름 및 매개변수 목록이 동일한 새 메서드를 수정하는 과정을 숨김이라고 합니다. 즉, 하위 클래스는 상위 클래스의 이 메서드를 숨깁니다. 그러나 숨김은 덮어쓰기와 다릅니다. 숨겨진 메서드는 해당 메서드가 있는 클래스를 통해서만 액세스할 수 있습니다. 상위 클래스의 변수를 사용하면 숨겨진 메서드에 계속 액세스할 수 있습니다.
위 코드를 보면 가리는 것과 숨기는 것의 차이를 알 수 있습니다. 상위 클래스 변수가 하위 클래스 인스턴스를 참조한 후에는 숨겨진 메서드에만 액세스할 수 있고 숨겨진 메서드에는 액세스할 수 없습니다. 그러나 재정의된 메서드에는 액세스할 수 있습니다.
또 다른 요점은 하위 클래스가 이 메서드를 재정의하려면 상위 클래스가 해당 메서드에 virtual을 추가해야 한다는 것입니다. 상위 클래스의 메서드를 숨기기 위해 new 키워드를 추가할 필요는 없습니다. Hide는 일반적으로 덜 사용되며 일부 특수한 상황에서 일부 문제를 해결합니다.

위 내용은 C# 기초지식 : 기초지식(7) 메소드의 숨은 내용을 모아 놓은 것입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!


원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!