【问题标题】:Cannot get attribute from PropertyInfo c#无法从 PropertyInfo c# 获取属性
【发布时间】:2015-04-24 20:00:17
【问题描述】:

我有一个这样的类和接口:

public partial interface INav_Item 
{
        [FieldID("df918977-369c-4a06-ac38-adb8741b5f75")]
        string Title  {get; set;}
}


public partial class Nav_Item  : INav_Item 
{
        [FieldID("df918977-369c-4a06-ac38-adb8741b5f75")]
        public virtual string Title  {get; set;}
}

然后我继承了这个类:

public class MenuItem : Nav_Item
{
        public virtual IEnumerable<MenuItem> Children { get; set; }

        //some other properties
}

我现在正在尝试实例化MenuItem 类型的对象,并尝试从继承类中获取属性(我无法直接实例化MenuItem,因为该类型是从其他类传入的)

object obj = Activator.CreateInstance(type);

foreach (PropertyInfo propInfo in type.GetProperties())
{
            FieldAttribute sfi =(FieldAttribute)propInfo.PropertyType.GetCustomAttribute(typeof(FieldAttribute));

}

但这让我sfi 成为null。我也调试过尝试获取所有属性:

propInfo.PropertyType.GetCustomAttributes()

.. 但这只是给我系统属性(类型和其他东西),但我自己的属性不在那里?这是因为类是继承的吗?如何获取属性值?

编辑:

属性类定义如下:

public class FieldIDAttribute : Attribute
{
    private string _id;

    public FieldAttribute(string Id)
    {
        _id = Id;
    }

    public ID TheFieldID
    {
        get
        {
            return new ID(_id);
        }
    }
}

【问题讨论】:

    标签: c# asp.net asp.net-mvc reflection attributes


    【解决方案1】:

    不,这不是继承问题。你需要改变这个:

    FieldAttribute sfi =(FieldAttribute)propInfo.PropertyType
        .GetCustomAttribute(typeof(FieldAttribute));
    

    到这里:

    var sfi = propInfo.GetCustomAttribute(typeof(FieldIDAttribute)) as FieldIDAttribute;
    

    这是因为 PropertyType 返回属性的类型,即在您的情况下为 string。而string 类型没有你的自定义属性。

    您对FieldIDAttribute 类的编辑也不正确。它的构造函数与类名不匹配,并且具有未声明且不正确的 ID 类型。

    【讨论】:

      【解决方案2】:

      除了 Alex 所说的,你应该指定绑定标志,这对我有用:

      foreach (PropertyInfo propInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
      {
                  FieldIDAttribute sfi = propInfo.PropertyType.GetCustomAttribute(typeof(FieldIDAttribute)) as FieldIDAttribute;
      
                  //Check if null here, if not, it has the attribute.
      
      }
      

      编辑:“类型”必须是 Nav_Item,您没有将 FieldIDAttribute 应用于 Menu_item 类中的任何内容。为了获取 IEnumerable 的属性,您必须遍历它并读取列表中每种元素的属性。

      【讨论】:

      • 不,那不是真的。如果您不指定绑定标志,它将包含typeof(MenuItem) 上的基类公共属性就好了。在他的具体代码示例(存在实例)中,他也可以使用更简单的:TypeDescriptor.GetProperties(obj)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 2011-03-29
      相关资源
      最近更新 更多