[英]How to get all enumerable properties of a specific type from a class
Lets say I have a poco class that looks like this:假设我有一个看起来像这样的 poco 类:
public MyClass
{
public IAssimilator p1 {get; set;}
public IAssimilator p2 {get; set;}
public IAssimilator p3 {get; set;}
public string n1 {get; set;}
public List<IAssimilator> p4 {get; set;}
public IEnumerable<IAssimilator> p5 {get; set;}
public List<int> n2 {get; set;}
}
I have a method elsewhere that returns a List
of all properties on MyClass that have type of IAssimilator
.我在别处有一个方法,它返回 MyClass 上具有
IAssimilator
类型的所有属性的List
。 It looks like this:它看起来像这样:
private List<IAssimilator> GetAssimilatorsOnClass(MyClass myInstance)
{
return typeof(MyClass).GetProperties()
.Where(p => p.PropertyType == typeof(IAssimilator))
.Select(p => p.GetValue(myInstance) as IAssimilator)
.ToList();
}
It will return a List<IAssimilator>
that contains the values of p1 thru p3.它将返回一个
List<IAssimilator>
,其中包含 p1 到 p3 的值。
What I would like to add is something to also get IAssimilator values inside any enumerable property.我想添加的是还可以在任何可枚举属性中获取 IAssimilator 值的内容。 In this case, it should return a List that contains the values in p4 and p5, but not n2.
在这种情况下,它应该返回一个列表,其中包含 p4 和 p5 中的值,但不包含 n2。 I don't really know where to start.
我真的不知道从哪里开始。
So you want to filter for all properties haveing a type which is IEnumerable<IAssimilator>
or derived from IEnumerable<IAssimilator>
.因此,您要过滤所有类型为
IEnumerable<IAssimilator>
或派生自IEnumerable<IAssimilator>
。 You can do this simimar to what you already did:你可以对你已经做过的事情做类似的事情:
private IEnumerable<IEnumerable<IAssimilator>> GetAssimilatorListsOnClass(MyClass myInstance)
{
typeof(MyClass)
.GetProperties()
.Where(p => typeof(IEnumerable<IAssimilator>).IsAssignableFrom(p.PropertyType))
.Select(p => p.GetValue(myInstance))
.Cast<IEnumerable<IAssimilator>>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.