无法从PropertyInfo获取属性c#

时间:2015-04-24 20:00:17

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

我有一个类和接口设置如下:

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类型的对象,并尝试从Inherited类中获取属性(我无法直接实例化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);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

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

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

到此:

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

这是因为PropertyType会返回属性的类型,即您的案例中的string。类型string没有您的自定义属性。

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

答案 1 :(得分:0)

除了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的属性,您必须枚举它并读取列表中每种元素类型的属性。

相关问题