我已经定义了一个自定义属性
[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. }
我错过了什么?
@H_502_14@解决方法
错字:应该是typeof(FieldAttribute).有一个不相关的系统枚举叫做FieldAttributes(在System.Reflection中,你在using指令中有,因为PropertyInfo正确解析).
此外,这更容易使用(假设该属性不允许重复):
var field = (FieldAttribute) Attribute.GetCustomAttribute( property,typeof (FieldAttribute),false); if(field != null) { Console.WriteLine(field.Field); }@H_502_14@ @H_502_14@ 原文链接:https://www.f2er.com/csharp/239112.html