如何查明类型是否实现泛型基类
本文关键字:泛型 基类 实现 是否 何查明 类型 | 更新日期: 2023-09-27 18:18:22
使用下面的例子…我怎样才能知道一个属性是否属于实现泛型类Foo的类型?
public class Foo<TBaz>
{
}
public class Bar
{
public Foo<int> FooInt { get; set; }
public Foo<string> FooString { get; set; }
public double SomeOther { get; set; }
public int GetFooCount()
{
return typeof(Bar).GetProperties().Where(p => p.GetType().IsGenericType).Count();
}
}
如果我想找到Foo<int>
,这很容易,但我怎么能找到它是否包含Foo<int>
, Foo<double>
等?
我已经写了GetFooCount()的位,我已经到目前为止…
谢谢
return typeof(Bar).GetProperties().Where(p => p.PropertyType.IsGenericType
&& p.PropertyType.GetGenericTypeDefinition() == typeof(Foo<>)).Count();
注意:这不会自动为class NonGenericSubtype : Foo<Blah> {...}
工作,也不会为class GenericSubtype<T> : Foo<T> {...}
工作-如果你需要处理这些,它会变得更有趣。
对于更一般的情况,您需要在类型上使用递归:
public static int GetFooCount()
{
return typeof(Bar).GetProperties()
.Count(p => GetFooType(p.PropertyType) != null);
}
private static Type GetFooType(Type type)
{
while(type != null)
{
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Foo<>))
return type.GetGenericArguments()[0];
type = type.BaseType;
}
return null;
}
注意,这也回答了"现在我如何找到T
?"