首页 > 解决方案 > 基于子类更改对象中属性的实际值

问题描述

问题:我已经以这种形式创建了对象:

Animal temporalAnimal = new Dog("Dog", "Ace","Boxer");
                               //Type //Name //Race

Animal 是基类, Dog 是子类。Type 和 Name 来自于 Animal,Race 来自于 Dog 类。我想将 temporalAnimal 中“Race”的值更改为“Shiba Inu”,但我无法访问该属性(它在子类上是公共的),我该如何修改他的值?

string type;
public string Type
{
    get { return type; }
    set { type = value; }
}

标签: c#oopinheritancepropertiessubclass

解决方案


如果您的引用是基类类型的,则您无法访问子类的属性(和方法)。您必须首先转换为子类,然后更改值:

Animal temporalAnimal = new Dog("Dog", "Ace","Boxer");
                               //Type //Name //Race

((Dog)temporalAnimal).Race = "Shiba Inu";

请注意,这实际上并没有改变 的类型temporalAnimal,但它确实为您提供了它所持有的确切类型的参考。


推荐阅读