简体   繁体   中英

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

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.

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.)

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;
    }
}

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