[英]Reflection: Type of item contained in non-generic subclass of generic list
public class MyList : List<MyClass>
如果我有一个包含MyList
实例的object
,如何通过反射获取MyClass
类型? 列表可以为空,所以我不能做像myList[0].GetType()
这样的事情。
ps我不能只停止使用MyList
并直接使用通用List(情况有点复杂,并且有“隐藏”泛型参数的原因),所以我无法通过GetGenericArguments()
获取MyClass
。
var elementType = (
from iface in myList.GetType().GetInterfaces()
where iface.IsGenericType
where iface.GetGenericTypeDefinition() == typeof(IList<>)
select iface.GetGenericArguments()[0])
.Single();
我使用IList<T>
而不是list。 这更通用。 但是,还有一个实现多个ILis<T>
版本的类型的更改(例如IList<string>
和IList<int>
)。
你可以得到基类型,它将是List<MyClass>
; 从中你可以使用GetGenericArguments获取泛型类型参数。
MyList list = new MyList();
Type baseTypeGenericArgument = list.GetType().BaseType.GetGenericArguments()[0];
string argumentTypeName = baseTypeGenericArgument.GetType().FullName;
你的类是否实现了通用接口? 您可以使用以下代码:
Type argument = GetGenericArgument(typeof(MyList), typeof(IList<>));
//...
static Type GetGenericArgument(Type type, Type genericTypeDefinition) {
Type[] interfaces = type.GetInterfaces();
for(int i = 0; i < interfaces.Length; i++) {
if(!interfaces[i].IsGenericType) continue;
if(interfaces[i].GetGenericTypeDefinition() == genericTypeDefinition)
return interfaces[i].GetGenericArguments()[0];
}
return null;
}
没有接口,您可以尝试以下方法:
class A { }
class B { }
class G<T> { }
class G1<T> : G<A> { }
class G2 : G1<B> { }
//...
Type argument1 = GetGenericArgument(typeof(G2)); // B
Type argument2 = GetGenericArgument(typeof(G2),1 ); // A
//...
static Type GetGenericArgument(Type type, int level = 0) {
do {
if(type.IsGenericType && 0 == level--)
return type.GetGenericArguments()[0];
type = type.BaseType;
}
while(type != null);
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.