【问题标题】:How can I use Reflection to get all fields of particular interface type如何使用反射来获取特定接口类型的所有字段
【发布时间】:2016-01-28 19:30:01
【问题描述】:

考虑以下接口

public interface ISample 
public interface ISample2 : ISample

public class A
{
    [Field]
    ISample SomeField {get; set;}

    [Field]
    ISample2 SomeOtherField {get; set; }
}

假设有各种类,如 A 类和各种字段,如 SomeField 和 SomeOtherField。 如何获取所有此类字段的列表,这些字段属于 ISample 类型或从 ISample 派生的其他接口(如 ISample2)

【问题讨论】:

  • 这些都不是字段。这些都是属性。

标签: c# .net reflection interface


【解决方案1】:

您可以使用ReflectionLinq 的组合来执行以下操作:

var obj = new A();
var properties = obj.GetType().GetProperties()
                    .Where(pi => typeof(ISample).IsAssignableFrom(pi.PropertyType))

在处理泛型时必须格外小心。但是对于您的要求,这应该很好

如果您想获取所有至少有一个属性返回ISample 子级的类,您将不得不使用程序集,例如,当前正在执行的

Assembly.GetExecutingAssembly().GetTypes()
        .SelectMany(t => t.GetProperties().Where(pi => // same code as the sample above)

如果你有几个程序集要探测,你可以使用这样的东西

IEnumerable<Assembly> assemblies = ....
var properties = assemblies
            .SelectMany(a => a.GetTypes().SelectMany(t => t.GetProperties()...))

【讨论】:

  • 你不需要A的实例,你可以使用typeof(A).GetProperties()...
  • @CraigW。是的,我知道我只是想非常明确以避免任何混淆。谢谢你的评论,虽然我真的忘了说
  • 如前所述,有各种类,如 class A.@CraigW 、@Luiso
  • 所以您想获取所有具有可从ISample 分配的类型的属性的类?在这种情况下,必须使用 Assembly
  • 您的IsAssignableFrom() 倒退了。 typeof(ISample).IsAssignableFrom(pi.PropertyType)public virtual bool IsAssignableFrom( Type c ) -> c 直接或间接派生自当前实例或当前实例是 c 实现的接口。
猜你喜欢
  • 2016-05-13
  • 1970-01-01
  • 2013-04-08
  • 2010-10-07
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多