How to access the properties of an instance of a d

2019-09-02 06:25发布

问题:

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