我有一个集合ot类型:
List<Type> types;
而且我想找出这些类型中的哪些类型是从具体的泛型类继承而来的,而无需关心T:
public class Generic<T>
我尝试过:
foreach(Type type in types)
{
if (typeof(Generic<>).IsAssignableFrom(type))
{
....
}
}
但是总是返回false,这可能是由于泛型元素造成的。有任何想法吗?
提前致谢。
AFAIK,没有类型报告为从开放的通用类型继承:我怀疑您将不得不手动循环:
static bool IsGeneric(Type type)
{
while (type != null)
{
if (type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(Generic<>))
{
return true;
}
type = type.BaseType;
}
return false;
}
然后,子列表为:
var sublist = types.FindAll(IsGeneric);
或者:
var sublist = types.Where(IsGeneric).ToList();
或者:
foreach(var type in types) {
if(IsGeneric(type)) {
// ...
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句