【问题标题】:Change actual value of a property in an Object based on Subclass基于子类更改对象中属性的实际值
【发布时间】:2019-01-25 10:19:08
【问题描述】:

问题:我有一个以这种形式创建的对象:

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# oop inheritance properties subclass


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    相关资源
    最近更新 更多