长话短说,我有一个 C# 函数,它对作为对象实例传入的给定类型执行任务。当传入类实例时,一切正常。但是,当对象被声明为接口时,我真的很想找到具体的类并对该类类型执行操作。
这是普遍存在的错误示例(例如不正确的属性大小写等):
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
}
我希望 PerformAction 中的代码对其参数使用反射,并看到它不仅仅是 IA 的实例,而且是 B 的实例,并通过 GetProperties() 查看属性“b”。如果我使用 .GetType() 我得到 IA 的类型 - 不是我想要的。
PerformAction 如何确定 IA 实例的底层具体类型?
有些人可能会建议使用抽象类,但这只是我的坏例子的局限性。该变量最初将被声明为接口实例。
Type objectType = myObject.GetType();
根据您的示例,仍然应该为您提供具体类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)