我想知道如何在以下场景中使用反射机制:
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; }
}
Run Code Online (Sandbox Code Playgroud)
然后我想找一个属性,该类型继承了该类型 ICollection<B>
var container = new Container();
var found = container.GetType().GetProperties().FirstOrDefault(x => x.PropertyType == typeof(ICollection<B>));
Run Code Online (Sandbox Code Playgroud)
当然found
变量是null,那么如何用反射更深入?
List<B>
当然不是同一类型ICollection<B>
.这是你的==
失败.
您需要检查属性类型是否可以分配给ICollection<B>
:
var found = typeof(Container).GetProperties()
.FirstOrDefault(x => typeof(ITest<B>).IsAssignableFrom(x.PropertyType));
Run Code Online (Sandbox Code Playgroud)
或者,您可以检查实现的接口PropertyType
:
var found = typeof(Container).GetProperties()
.FirstOrDefault(x => x.PropertyType.GetInterfaces().Contains(typeof(ICollection<B>)));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
43 次 |
最近记录: |