查找接口实例背后的具体类型 [英] Finding the Concrete Type behind an Interface instance

查看:168
本文介绍了查找接口实例背后的具体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要削减长话短说我有执行上的传递作为对象实例的给定类型任务的C#的功能。当一个类的实例中传递的所有工作正常。但是,当对象被声明为接口我真的想找到具体的类,并执行在对该类类型的操作。



下面是无处不在坏榜样(金碧辉煌不正确的属性套管等):

 公共接口IA 
{
int类型的{搞定;组; }
}
公共B类:IA
{
公众诠释一个{搞定;组; }
公众诠释B {搞定;组; }
}
公共类C:IA
{
公众诠释一个{搞定;组; }
公众诠释三{搞定;组; }
}

//剪断

IA myBObject =新的B();
的performAction(myBObject);

IA myCObject =新C();
的performAction(myCObject);

//剪断

的performAction无效(对象myObject的)
{
型的objectType = myObject.GetType(); //这里就是我得到的typeof(IA)
如果(objectType.IsInterface)
{
//我要确定实际的具体类型,即无论是B或C
//的objectType = DetermineConcreteType(的objectType);
}
//喀嚓 - 上的objectType
}
其他动作

我想的performAction中的代码使用反射反对它的参数,并看到它不只是IA的实例,但是,它是b的实例,并通过GetProperties,用于查看属性b()。如果我使用.GetType()我得到IA的类型 - ?不是我想要的。



如何的performAction能确定IA的实例的基础混凝土类型



有些人也许会用一个抽象类建议,但是这是我的坏榜样的只是限制。变量将原本声明为接口的实例。


解决方案

 键入的objectType = myObject的。的GetType(); 



还是应该给你的具体类型,根据你的榜样。


To cut a long story short I have a C# function that performs a task on a given Type that is passed in as an Object instance. All works fine when a class instance is passed in. However, when the object is declared as an interface I'd really like to find the concrete class and perform the action upon that class type.

Here is the ubiquitous bad example (resplendent with incorrect property casing etc):

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

// snip

IA myBObject = new B();
PerformAction(myBObject);

IA myCObject = new C();
PerformAction(myCObject);

// snip

void PerformAction(object myObject)
{
    Type objectType = myObject.GetType();   // Here is where I get typeof(IA)
    if ( objectType.IsInterface )
    {
        // I want to determine the actual Concrete Type, i.e. either B or C
        // objectType = DetermineConcreteType(objectType);
    }
    // snip - other actions on objectType
}

I'd like the code in PerformAction to use Reflection against it's parameter and see that it's not just an instance of IA but that it's an instance of B and to see the property "b" via GetProperties(). If I use .GetType() I get the Type of IA - not what I want.

How can PerformAction determine the underlying Concrete Type of the instance of IA?

Some might be tempted to suggest using an Abstract class but that is just the limitation of my bad example. The variable will be originally declared as an interface instance.

解决方案

Type objectType = myObject.GetType();

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

这篇关于查找接口实例背后的具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆