簡體   English   中英

使用Reflection獲取未由接口實現的對象的所有屬性

[英]Using Reflection to get all properties of an object not implemented by an interface

我希望能夠使用反射來遍歷不實現接口的對象的屬性

基本上我想實現與此相反的如何使用反射來獲取顯式實現接口的屬性?

原因是我想將對象映射到另一個對象,其中任何未由接口定義的屬性被添加到KeyValuePairs的List中。

使用此示例:

interface IFoo
{
  string A { get; set; }
}
class Foo : IFoo
{
  public string A { get; set; }
  public string B { get; set; }
}

然后使用此代碼,我只得到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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM