无法使用反射获取泛型类型的属性



我只是在这里简单地回答这个问题,所以这个例子对现实世界没有任何意义。

public class BusinessEntity<T>
{
    public int Id {get; set;}
}
public class Customer : BusinessEntity<Customer>
{
    public string FirstName { get; set;}
    public string LastName { get; set;}
}

当我试图通过反射获得Customer类的属性时,我无法获得泛型基类的属性。如何从业务实体获取Id?

Type type = typeof(Customer);
PropertyInfo[] properties = type.GetProperties(); 
// Just FirstName and LastName listed here. I also need Id here 

没有,这肯定会返回所有3个属性。检查真实代码中的Id是否为internal/protected/etc(即非公共)。如果是,您需要通过BindingFlags,例如:

PropertyInfo[] properties = type.GetProperties(
    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

(默认为public+instance+static)

还要检查它是否不是实际代码中的字段;如果是:

public int Id;

则它是一个字段,您应该使用GetFields使Id成为属性;p

问题是什么,您的代码非常好,并返回正确的属性

Type type = typeof(Customer);
PropertyInfo[] properties = type.GetProperties(); 
foreach(var prop in properties)
{ Console.WriteLine(prop) }

结果

System.String FirstName 
System.String LastName 
Int32 Id

为了获得基本属性,您必须使用类型的BaseType属性

PropertyInfo[] baseProperties = typeof(Customer).BaseType.GetProperties(BindingFlags.DeclaredOnly);
PropertyInfo[] properties = typeof(Customer).GetProperties(); 

最新更新