Finding the Concrete Type behind an Interface instance

早过忘川 提交于 2019-11-28 05:14:47
Type objectType = myObject.GetType();

Should still give you the concrete type, according to your example.

What are you doing is really bed design but you don't have to use reflection you can check it like this

void PerformAction(object myObject)
{
    B objectType = myObject as B;   // Here is where I get typeof(IA)
    if ( objectType != null )
    {
        //use objectType.b
    }
    else
    {
       //Same with A 
    }
    // snip - other actions on objectType
}

I have to agree about the bad design. If you have an interface, it should be because you need to utilize some common functionality without caring what the concrete implementation is. Given you're example, it sounds like the PerformAction method should actually be a part of the interface:

public interface IA
{
    int a { get; set; }
    void PerformAction();
}

public class B: IA
{
    public int a { get; set; }
    public int b { get; set; }

    public void PerformAction()
    {
        // perform action specific to B
    }
}

public class C : IA
{
    public int a { get; set; }
    public int c { get; set; }

    public void PerformAction()
    {
        // perform action specific to C
    }
}

void PerformActionOn(IA instance)
{
    if (instance == null) throw new ArgumentNullException("instance");

    instance.PerformAction();

    // Do some other common work...
}


B b = new B();
C c = new C();

PerformActionOn(b);
PerformActionOn(c);

You can never have instances of an Interface. So determining whether you are dealing with an interface or a concrete type is not possible since you will always be dealing with a concrete type. So I am not sure you question makes any sense. What exactly are you trying to do and why?

Maybe you are looking for the is operator

void PerformAction(object myObject)
{
    if (myObject is B)
    {
        B myBObject = myObject as B;
        myBObject.b = 1;
    }

    if (myObject is C)
    {
        C myCObject = myObject as C;
        myCObject.c = 1;
    }

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