2017-08-11 134 views
0

我想知道如何使用反射机制在以下情况下属性:C#反射找到哪种类型的继承一些其他类型的

public class A { } 
public class B { } 

public class ListA : ICollection<A> { } 

public class ListB : ICollection<B> { } 

public class Container 
{ 
    public ListA LA { get; set; } 
    public ListB LB { get; set; } 
} 

那么我想找到一个属性,该属性类型继承类型ICollection<B>

var container = new Container(); 

var found = container.GetType().GetProperties().FirstOrDefault(x => x.PropertyType == typeof(ICollection<B>)); 

并且当然found变量为空,那么如何更深入地反思?

回答

5

List<B>当然不是与ICollection<B>相同的类型。这就是你的==失败。

您需要检查,如果属性类型可以被分配给一个ICollection<B>

var found = typeof(Container).GetProperties() 
       .FirstOrDefault(x => typeof(ITest<B>).IsAssignableFrom(x.PropertyType)); 

另外,您可以检查PropertyType实现的接口:

var found = typeof(Container).GetProperties() 
       .FirstOrDefault(x => x.PropertyType.GetInterfaces().Contains(typeof(ICollection<B>))); 
+0

我是否正确理解第一种方法应该与类一起工作呢? –

+1

@SamvelPetrosov是的。 –

1

在情况下,如果你想获得实现一些接口的类,在你的情况下它是ICollection<B>,你可以使用下面的代码使用Reflection的GetInterfaces()方法:

var container = new Container(); 

var found = container.GetType().GetProperties().FirstOrDefault(x => x.PropertyType.GetInterfaces().Contains(typeof(ICollection<B>)));