有时在 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; } }}如何访问隐藏的属性?(动物.品种)
1 回答
胡子哥哥
TA贡献1825条经验 获得超6个赞
您正在寻找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;
}
}
}
- 1 回答
- 0 关注
- 115 浏览
添加回答
举报
0/150
提交
取消
