How to access the properties of an instance of a derived class which is passed as a parameter in the form of the base class

余生颓废 提交于 2019-12-12 03:59:46

问题


In C# I have a base class and a derived class.

I have a function which has the base class as an input parameter

public void SomeFunction(BaseClass InstanceOfDerivedClass)

Is there a way I can access the properties specific to the derived class, even though it has been passed as a base class? Could I use GetType or Cast or something like that?

I appreciate that the solutions may not be elegant but at the moment the alternative is to repeat this function many times for the different derived classes.


回答1:


you could do this (bad way):

public void SomeFunction(BaseClass instanceOfDerivedClass)
{
    DerivedClass derived = null;

    if(instanceOfDerivedClass is DerivedClass)
    {
        derived = instanceOfDerivedClass as DerivedClass;
        // Do stuff like :
        int prop = derived.DerivedProperty;
    }
}

Or, as suggested by Eric (good way):

public void SomeFunction(BaseClass instanceOfDerivedClass)
{
    DerivedClass derived = instanceOfDerivedClass as DerivedClass;

    if(derived != null)
    {
        // Do stuff like :
        int prop = derived.DerivedProperty;
    }
}



回答2:


Casting should definitely do the trick, since the reference in the heap is to that class. Maybe something like:

if (InstanceOfDerivedClass is DerivedClass)

And in that block you can cast it and interact with it.

But the bigger question is, why do you need to? It sounds like this method is using the wrong abstraction if the type being accepted as an argument isn't the correct type. This is breaking Liskov Substitution and looks like a prime candidate for refactoring the design. (Of which we don't know enough to help much.)



来源:https://stackoverflow.com/questions/7587667/how-to-access-the-properties-of-an-instance-of-a-derived-class-which-is-passed-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!