【问题标题】:Could not get the properties of a generic type by using reflection无法使用反射获取泛型类型的属性
【发布时间】:2012-07-25 07:54:19
【问题描述】:

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

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 类属性时,我无法获取泛型基类的属性。如何从 BusinessEntity 获取 ID?

Type type = typeof(Customer);

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

【问题讨论】:

  • 刚刚测试过,我返回的属性数组总是有3个条目(VS2012,尝试了多个目标框架)。
  • "如何从 BusinessEntity 获取 ID?"去洗眼睛? :p
  • 诀窍是:当您简化问题的代码时,检查它是否仍然显示问题。如果确实没有显示问题,那么看看真实代码和简化代码有什么不同,然后你就自己回答了
  • 我现在在笑自己(:谢谢大家。也非常感谢您的好意建议。

标签: c# .net reflection


【解决方案1】:

不,这肯定会返回所有 3 个属性。在您的真实代码中检查Id 是否为internal / protected / 等(即非公开)。如果是,则需要传入BindingFlags,例如:

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

(默认为公共+实例+静态)

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

public int Id;

那么它是一个字段,你应该使用GetFields 使Id成为一个属性 ;p

【讨论】:

  • 实际上它已被声明为您提到的字段。我的坏(:谢谢
  • +1 因为我从上面的 cmets 中学到了一些新东西
【解决方案2】:

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

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

结果

System.String FirstName 
System.String LastName 
Int32 Id

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 事情是……这不是真的。默认情况下,您将获得继承的属性。事实上,你必须传递额外的标志来得到它们。
    • @MarcGravell 是的,我同意,但这是获取类型基础属性的一种方式
    • 嗯,有点;如果你这样做,你可能想要指定DeclaredOnly,否则你会加倍
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 2018-06-05
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多