[英]Using Reflection to get all properties of an object not implemented by an interface
I want to be able use reflection to loop through the properties of an object that DO NOT implement an interface 我希望能够使用反射来遍历不实现接口的对象的属性
Essentially I want to achieve the opposite of this How do I use reflection to get properties explicitly implementing an interface? 基本上我想实现与此相反的如何使用反射来获取显式实现接口的属性?
The reason is I want to map objects to another object where any properties that are not defined by an interface are added instead to a List of KeyValuePairs
. 原因是我想将对象映射到另一个对象,其中任何未由接口定义的属性被添加到KeyValuePairs
的List中。
Using this example: 使用此示例:
interface IFoo
{
string A { get; set; }
}
class Foo : IFoo
{
public string A { get; set; }
public string B { get; set; }
}
Then using this code, I get only PropertyInfo
for B
. 然后使用此代码,我只得到B
PropertyInfo
。
var fooProps = typeof(Foo).GetProperties();
var implementedProps = typeof(Foo).GetInterfaces().SelectMany(i => i.GetProperties());
var onlyInFoo = fooProps.Select(prop => prop.Name).Except(implementedProps.Select(prop => prop.Name)).ToArray();
var fooPropsFiltered = fooProps.Where(x => onlyInFoo.Contains(x.Name));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.