从子类访问隐藏的属性

有时在 C# 中隐藏继承的基类的属性很有用,例如当您想要更改类型时。但是,一旦我隐藏了继承的属性,我不知道如何读取或写入隐藏属性的值。


这是一个使用动物和狗的小例子:


public enum DogBreed {

    Corgi, Pug

}

public class Animal {

    public string Breed { get; set; }

}

public class Dog : Animal {

    public new DogBreed? Breed {

        get {

            // Not working since "Breed" now refers to Dog.Breed not Animal.Breed

            if (Breed == "Corgi") return DogBreed.Corgi;

            if (Breed == "Pug") return DogBreed.Pug;

            return null;

        }

        set {

            // Also Not working for same reason as above

            if (value == DogBreed.Corgi) Breed = "Corgi";

            else if (value == DogBreed.Pug) Breed = "Pug";

            else Breed = null;

        }

    }

}

如何访问隐藏的属性?(动物.品种)


qq_遁去的一_1
浏览 116回答 1
1回答

胡子哥哥

您正在寻找base关键字:public class Dog : Animal {    public new DogBreed? Breed {        get {            // base.Breed refers to the hidden property            if (base.Breed == "Corgi") return DogBreed.Corgi;            if (base.Breed == "Pug") return DogBreed.Pug;            return null;        }        set {            if (value == DogBreed.Corgi) base.Breed = "Corgi";            else if (value == DogBreed.Pug) base.Breed = "Pug";            else base.Breed = null;        }    }}
打开App,查看更多内容
随时随地看视频慕课网APP