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; }


   }
}

しかし、カスタム属性の値を取得しようとすると、nullオブジェクトが返されます

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

タイプミス:する必要がありますtypeof(FieldAttribute)。と呼ばれる無関係のシステム列挙型がありますFieldAttributes(正しく解決されるため、ディレクティブにSystem.Reflectionあります)。usingPropertyInfo

また、これはより簡単な使用法です(属性が重複を許可しないと仮定します):

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