C#反射匹配类型列表<;T>;其中T为B类(Foo)

C#反射匹配类型列表<;T>;其中T为B类(Foo),c#,.net,generics,reflection,C#,.net,Generics,Reflection,我有一个类,它包含List的属性。在这些属性中,T属于从类继承的类,比如Foo 公共类Foo{} 公共类MyTypeA:Foo{} 公共类MyTypeB:Foo{} //不是:福 公共类MyTypeC{} 公共类酒吧 { //我能配得上这些 公共MyTypeA PropA{get;set;} 公共MyTypeB PropB{get;set;} //如何根据IsSubclassOf(Foo)匹配这些 公共列表PropListA{get;set;} 公共列表PropListB{get;set;} /

我有一个类,它包含
List
的属性。在这些属性中,T属于从类继承的类,比如Foo

公共类Foo{}
公共类MyTypeA:Foo{}
公共类MyTypeB:Foo{}
//不是:福
公共类MyTypeC{}
公共类酒吧
{
//我能配得上这些
公共MyTypeA PropA{get;set;}
公共MyTypeB PropB{get;set;}
//如何根据IsSubclassOf(Foo)匹配这些
公共列表PropListA{get;set;}
公共列表PropListB{get;set;}
//不要匹配下面的道具
公共MyTypeC PropC{get;set;}
公共列表PropListC{get;set;}
公共列表PropListString{get;set;}
}    
我已经成功地匹配了
Foo
的子类属性,如下所示

foreach(T.GetProperties(BindingFlags.Public | BindingFlags.Instance)中的var oProp)
{
//查找道具:Foo
if(oProp.PropertyType.IsSubclassOf(typeof(Foo)))
{
//将属性添加到字典
aPropInheritType.Add(
操作名,
奥普拉普
);
}
//匹配列表,其中T:Foo
//如何测试T类型是子类的泛型列表
//你是班上的学生吗?
}

我看到Type类有许多泛型属性,但还无法获取泛型列表的类型,然后根据IsSubclassOf(Foo)进行测试。

这里是我从Microsoft框架中偷来的一点宝石(我认为它是在EF二进制文件中)


这是我从微软框架中偷来的一块小宝石(我想它是在EF二进制文件中)


要测试属性是否具有返回类型
列表
,请使用下一个代码:

Type returnType = oProp.PropertyType;
if(returnType.IsGenericType && 
   returnType.GetGenericTypeDefinition() == typeof(List<>) &&
   typeof(Foo).IsAssignableFrom(returnType.GetGenericArguments()[0]))
{
   //property is of type List<T>, where T is derived from Foo
}
Type returnType=oProp.PropertyType;
if(returnType.IsGenericType&&
returnType.GetGenericTypeDefinition()==typeof(列表)&&
typeof(Foo).IsAssignableFrom(returnType.GetGenericArguments()[0]))
{
//属性的类型为List,其中T派生自Foo
}

要测试属性是否具有返回类型
列表
,请使用下一个代码:

Type returnType = oProp.PropertyType;
if(returnType.IsGenericType && 
   returnType.GetGenericTypeDefinition() == typeof(List<>) &&
   typeof(Foo).IsAssignableFrom(returnType.GetGenericArguments()[0]))
{
   //property is of type List<T>, where T is derived from Foo
}
Type returnType=oProp.PropertyType;
if(returnType.IsGenericType&&
returnType.GetGenericTypeDefinition()==typeof(列表)&&
typeof(Foo).IsAssignableFrom(returnType.GetGenericArguments()[0]))
{
//属性的类型为List,其中T派生自Foo
}

可能是Go to and search for“generic”的副本对于
列表的子类(例如
ObservableCollection
),或者对于
列表,其中T:Foo
,您需要一个肯定的结果吗?可能是Go to and search for“generic”的副本对于
列表的子类,您需要一个肯定的结果吗(例如
ObservableCollection
),或者对于
列表中的T:Foo
?非常感谢Ilya!使用IsAssignableFrom:GetGenericArguments()[0]有什么好处吗?IsubClassof(typeof(Foo))@hokapoka是,
typeof(Foo).IsubClassof(typeof(Foo))
将返回false,而
IsAssignableFrom
将返回true。在您的情况下,您可能需要
IsAssignableFrom
非常感谢Ilya!使用IsAssignableFrom有什么好处吗:GetGenericArguments()[0]。IsSubclassOf(typeof(Foo))@hokapoka是的,
typeof(Foo)。IsSubclassOf(typeof(Foo))
将返回false,而
IsAssignableFrom
将返回true。在您的情况下,您可能需要
IsAssignableFrom
Type returnType = oProp.PropertyType;
if(returnType.IsGenericType && 
   returnType.GetGenericTypeDefinition() == typeof(List<>) &&
   typeof(Foo).IsAssignableFrom(returnType.GetGenericArguments()[0]))
{
   //property is of type List<T>, where T is derived from Foo
}