简体   繁体   中英

Can not access derived class fields using base class

I am not able to access simple field from derived class so what is use of polymorphism in case of fields. If I have to downcast to ResponseMBP to get the Name property then my client needs to know about derived class.

So does polymorphism work only for methods?

public abstract class Response
{
}

public class ResponseMbp : Response
{        
    public string Name = "My Name";        
}

class Program
{
    static void Main(string[] args)
    {
        Response r = new ResponseMbp();
        Console.Write(r.Name);
    }
}

You are defining your variable as type Response . At this point you can only access properties and variables that are contained in the Response class and its superclasses.

You're also trying to refer to Name while the property is named name .

First of all for field polymorphism, you should have that field declared in both the base and derived class (as is the case with method polymorphism).

Now in you example, the field "name" is only part of derived class signature, and you do not have "name" variable in the signature of your base class. Due to this the object of your base class, though it is instantiated with derived class, would only show you base class signature items. Thus due to this reason, you are not able to use r.name in your example.

To know proper usage of field polymorphism, refer this link.

ResponseMbp is inheriting from Response . So ResponseMbp is a Response , but a Response is not a ResponseMbp .

Since you are defining the property Name in ResponseMbp , Response does not know, or care, about it.

If you defined Name in Response , ResponseMbp would inherit the property, and it would be accessible from either class.

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