[英]Get implementer class instance from the interface instance
我有一些实现接口的类:
class FirstImplementer : IInterface { ... }
class AnotherImplementer : IInterface { ... }
在代码中的某个地方,我得到了IInterface实例的列表。
List<IInterface> MyList;
我想知道每个IInterface实例的特定实例(FirstImplementer或AnotherImplementer)的实现者类是什么。
你可以只用.GetType()
上的情况下MyList
并从那里走。
MyList[0].GetType()
>与typeof(FirstImplementer)
等相同。
foreach (var item in MyList)
{
var theType = item.GetType();
// why did you want theType, again?
// you generally shouldn't be concerned with how your interface is implemented
}
根据您要执行的操作,此替代方法可能会更有用:
foreach (var item in MyList)
{
if (item is FirstImplementer)
{
var firstImpl = (FirstImplementer)item;
// do something with firstImpl
}
else if (item is AnotherImplementer)
{
var anotherImpl = (AnotherImplementer)item;
// do something with anotherImpl
}
}
通常最好在可能的情况下使用is
或as
over Reflection(例如GetType
)。
foreach (var instance in MyList)
{
Type implementation = instance.GetType ();
}
如果您需要获取第一个类型参数(如果有),并且如果列表中的每个实例都不存在此类参数,则为null(在设计时,您在语法上将其视为接口引用),则可以使用Type类型的GetGenericArguments方法。
这是一个小帮手方法,它接收一堆可能为null的对象,但如果没有则肯定会实现您的接口(它们会有运行时类型),并产生一堆表示(按各自顺序)的类型)在SomeImplementer模式中发现的类型参数:
public IEnumerable<Type> GetTypeArgumentsFrom(IEnumerable<IInterface> objects) {
foreach (var obj in objects) {
if (null == obj) {
yield return null; // just a convention
// you return null if the object was null
continue;
}
var type = obj.GetType();
if (!type.IsGenericType) {
yield return null;
continue;
}
yield return type.GetGenericArguments()[0];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.