6

我已经定义了一个自定义属性

[AttributeUsage(AttributeTargets.Property )]
public class FieldAttribute: Attribute
{
    public FieldAttribute(string field)
    {
        this.field = field;
    }
    private string field;

    public string Field
    {
        get { return field; }

    }
}

使用自定义属性的我的类如下

[Serializable()]   
public class DocumentMaster : DomainBase
{

    [Field("DOC_CODE")]
    public string DocumentCode { get; set; }


    [Field("DOC_NAME")]
    public string DocumentName { get; set; }


    [Field("REMARKS")]
    public string Remarks { get; set; }


   }
}

但是当我尝试获取自定义属性的值时,它返回空对象

Type typeOfT = typeof(T);
T obj = Activator.CreateInstance<T>();

PropertyInfo[] propInfo = typeOfT.GetProperties();

foreach (PropertyInfo property in propInfo)
{

     object[] colName = roperty.GetCustomAttributes(typeof(FieldAttributes), false);
     /// colName has no values.
}

我错过了什么?

4

1 回答 1

9

typo: should be typeof(FieldAttribute). There is an unrelated system enum called FieldAttributes (in System.Reflection, which you have in your using directives, since PropertyInfo resolves correctly).

Also, this is easier usage (assuming the attribute doesn't allow duplicates):

var field = (FieldAttribute) Attribute.GetCustomAttribute(
          property, typeof (FieldAttribute), false);
if(field != null) {
    Console.WriteLine(field.Field);
}
于 2012-04-25T12:34:53.957 回答