简体   繁体   中英

Checking concrete type of inheriting classes

Let's say I have a couple of classes:

public class BaseClass
{
    //....
}

public class ChildClassA : BaseClass
{
    //....
}

public class ChildClassB : BaseClass
{
    //....
}

Now I have another class which uses the child classes above:

public class Program
{
    private Type _type;
    private ChildClassA _childA = GetChildClassA();
    private ChildClassB _childB = GetChildClassB();

    public void MethodOne()
    {
        if(_type == typeof(ChildClassA))
            DoSomething(_childA);
        else if(_type == typeof(ChildClassB))
            DoSomething(_childB);
    }

    public void MethodTwo()
    {
        if(_type == typeof(ChildClassA))
            DoSomething(_childA);
        else if(_type == typeof(ChildClassB))
            DoSomething(_childB);
    }
}

Let's say I have the if clause inside MethodOne and MethodTwo over and over again in my code, how can I make this cleaner? With an interface, I can just declare one class variable IBaseClass and assign _childA or _childB to it. But with inherited classes, this isn't possible. Is there some other way to get the same result? So basically I would end up with something like this:

public class Program
{
    private IBaseClass _child = GetChildClass();

    public void MethodOne()
    {
        DoSomething(_child);
    }

    public void MethodTwo()
    {
        DoSomething(_child);
    }
}

EDIT: To clarify, I can't use interfaces as all the classes have already been implemented since a long time ago and refactoring them would be a huge undertaking. So I am basically looking for doing something similar with base and child classes.

EDIT2: Here is what I meant with my comment on HimBromBeere's answer:

private void DoSomething(BaseClass baseC)
{
    var childA = baseC as ChildClassA;

    if (childA != null)
        childA.DoSomethingA();

    var childB = baseC as ChildClassB;

    if(childA != null)
        childB.DoSomethingB();
}

Seems like you want to indicate at runtime which behaviour to use by switching on the actual type, which is what polymorphism is about.

You won´t need an interface, as you already have a common base-class. So just change private IBaseClass _child = GetChildClass() to private BaseClass _child = GetChildClass() :

public class Program
{
    private BaseClass _child = GetChildClass();

    public void MethodOne()
    {
        DoSomething(_child);
    }

    public void MethodTwo()
    {
        DoSomething(_child);
    }
}

This assumes DoSomething just expects a BaseClass as parameter.

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