C# 如何从TypeInfo获取声明和继承的成员
在中,声明的*属性是访问类型上声明的成员(字段、属性、方法等)的正确方法。但是,这些属性不包括从基类继承的成员 旧的C# 如何从TypeInfo获取声明和继承的成员,c#,inheritance,reflection,.net-core,C#,Inheritance,Reflection,.net Core,在中,声明的*属性是访问类型上声明的成员(字段、属性、方法等)的正确方法。但是,这些属性不包括从基类继承的成员 旧的TypeInfo.GetRuntime*()方法返回声明的和继承的成员,但并非在所有平台上都可用,包括.NET Core 如何使用新API获取已声明和继承成员的列表?我编写了一组提供此功能的小型扩展方法: public static class TypeInfoAllMemberExtensions { public static IEnumerable<Constr
TypeInfo.GetRuntime*()
方法返回声明的和继承的成员,但并非在所有平台上都可用,包括.NET Core
如何使用新API获取已声明和继承成员的列表?我编写了一组提供此功能的小型扩展方法:
public static class TypeInfoAllMemberExtensions
{
public static IEnumerable<ConstructorInfo> GetAllConstructors(this TypeInfo typeInfo)
=> GetAll(typeInfo, ti => ti.DeclaredConstructors);
public static IEnumerable<EventInfo> GetAllEvents(this TypeInfo typeInfo)
=> GetAll(typeInfo, ti => ti.DeclaredEvents);
public static IEnumerable<FieldInfo> GetAllFields(this TypeInfo typeInfo)
=> GetAll(typeInfo, ti => ti.DeclaredFields);
public static IEnumerable<MemberInfo> GetAllMembers(this TypeInfo typeInfo)
=> GetAll(typeInfo, ti => ti.DeclaredMembers);
public static IEnumerable<MethodInfo> GetAllMethods(this TypeInfo typeInfo)
=> GetAll(typeInfo, ti => ti.DeclaredMethods);
public static IEnumerable<TypeInfo> GetAllNestedTypes(this TypeInfo typeInfo)
=> GetAll(typeInfo, ti => ti.DeclaredNestedTypes);
public static IEnumerable<PropertyInfo> GetAllProperties(this TypeInfo typeInfo)
=> GetAll(typeInfo, ti => ti.DeclaredProperties);
private static IEnumerable<T> GetAll<T>(TypeInfo typeInfo, Func<TypeInfo, IEnumerable<T>> accessor)
{
while (typeInfo != null)
{
foreach (var t in accessor(typeInfo))
{
yield return t;
}
typeInfo = typeInfo.BaseType?.GetTypeInfo();
}
}
}
这些扩展方法与desktop.NET 4.5+和.NET Core兼容
public class Test
{
[Fact]
public void Get_all_fields()
{
var fields = typeof(TestDerived).GetTypeInfo().GetAllFields();
Assert.True(fields.Any(f => f.Name == "FooField"));
Assert.True(fields.Any(f => f.Name == "BarField"));
}
[Fact]
public void Get_all_properties()
{
var properties = typeof(TestDerived).GetTypeInfo().GetAllProperties();
Assert.True(properties.Any(p => p.Name == "FooProp"));
Assert.True(properties.Any(p => p.Name == "BarProp"));
}
}
public class TestBase
{
public string FooField;
public int FooProp { get; set; }
}
public class TestDerived : TestBase
{
public string BarField;
public int BarProp { get; set; }
}