简体   繁体   中英

Change actual value of a property in an Object based on Subclass

Problem: I have and object created in this form:

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

Animal is the Base Class and Dog the Subclass. Type and Name are from Animal, and Race is from the Dog Class. I want to change the value of "Race" in temporalAnimal to "Shiba Inu", but i cant access to the property (It is Public on the Subclass), how can I modify his value ?

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

You can't access the properties (and methods) of the subclass if your reference is the of the base class type. You must first cast to the subclass and then change the value:

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

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

Please note that this does not actually change the type of temporalAnimal , but it does give you a reference to the exact type it's holding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM