【问题标题】:Using Reflection to get all properties of an object not implemented by an interface使用反射获取接口未实现的对象的所有属性
【发布时间】:2013-03-15 14:32:49
【问题描述】:

我希望能够使用反射来循环遍历未实现接口的对象的属性

基本上我想实现与How do I use reflection to get properties explicitly implementing an interface?相反的效果

原因是我想将对象映射到另一个对象,其中任何未由接口定义的属性都被添加到 KeyValuePairs 列表中。

【问题讨论】:

  • 没有任何实现接口。你的意思是你想要所有实现接口的属性?
  • @MatthewWatson:吹毛求疵,但是:你的意思是问 OP 他是否想要所有不参与接口实现的属性?
  • 对不起。以上都是。
  • @StewartAlan 请显示一些源代码...您尝试了什么?究竟是什么不工作?
  • @StewartAlan:接口是显式实现还是隐式实现?

标签: c# asp.net reflection


【解决方案1】:

使用这个例子:

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

然后使用此代码,我只得到PropertyInfoB

  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));

【讨论】:

  • 这是假设实现的属性名与接口上的属性名匹配,不一定如此。
  • @JonEgerton 因此Foo 中的A 可能是C,例如?
  • 这在 VB.Net 中是可能的,但不确定 C#。如果 OP 可以假设他没有使用 VB.Net 程序集,则可能不是问题。
  • @JonEgerton 看到标签是C# 我看不出这怎么可能。我知道这是否是VB.Net,因为您将拥有Public Property C As String Implements IFoo.A。据我所知,这在 C# 中无效。
  • 在 VB 中,您可以使用 Public Property C As String Implements IFoo.A 不确定是否可以使用 C# 的语法来实现。在您实现具有相同属性名称的接口时,它实际上很有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多