Skip to main content
 首页 » 编程设计

c#之如何使用反射获取特定接口(interface)类型的所有字段

2024年02月05日8artech

考虑以下接口(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 派生的其他接口(interface)(如 ISample2)的此类字段的列表

请您参考如下方法:

您可以结合使用 Reflection 和 Linq 来执行如下操作:

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()...))