如何使用Reflection获取特定接口类型的所有字段

时间:2015-10-28 20:26:50

标签: c# .net reflection interface

考虑以下接口

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)

1 个答案:

答案 0 :(得分:3)

您可以使用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()...))