有时在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;
}
}
}
如何访问隐藏的属性? (动物品种)
答案 0 :(得分:2)
您正在寻找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;
}
}
}