使用下面的示例...如何确定属性是否属于实现泛型类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
?”
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句