如何使用反射获取特定接口类型的所有字段
How can I use Reflection to get all fields of particular interface type
考虑以下接口
public interface ISample
public interface ISample2 : ISample
public class A
{
[Field]
ISample SomeField {get; set;}
[Field]
ISample2 SomeOtherField {get; set; }
}
假设有各种 classes,如 class A 和各种字段,如 SomeField 和 SomeOtherField。
我怎样才能获得所有此类字段的列表,这些字段属于 ISample 类型或从 ISample 派生的其他接口(如 ISample2)
您可以结合使用 Reflection
和 Linq
来执行以下操作:
var obj = new A();
var properties = obj.GetType().GetProperties()
.Where(pi => typeof(ISample).IsAssignableFrom(pi.PropertyType))
在处理泛型时必须格外小心。不过按照你的要求,这应该不错
如果你想让所有 类 至少有一个 属性 返回 child of 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()...))
考虑以下接口
public interface ISample
public interface ISample2 : ISample
public class A
{
[Field]
ISample SomeField {get; set;}
[Field]
ISample2 SomeOtherField {get; set; }
}
假设有各种 classes,如 class A 和各种字段,如 SomeField 和 SomeOtherField。 我怎样才能获得所有此类字段的列表,这些字段属于 ISample 类型或从 ISample 派生的其他接口(如 ISample2)
您可以结合使用 Reflection
和 Linq
来执行以下操作:
var obj = new A();
var properties = obj.GetType().GetProperties()
.Where(pi => typeof(ISample).IsAssignableFrom(pi.PropertyType))
在处理泛型时必须格外小心。不过按照你的要求,这应该不错
如果你想让所有 类 至少有一个 属性 返回 child of 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()...))