c# – GetCustomAttributes不返回值
发布时间:2020-12-15 08:15:13 所属栏目:百科 来源:网络整理
导读:我已经定义了一个自定义属性 [AttributeUsage(AttributeTargets.Property )]public class FieldAttribute: Attribute{ public FieldAttribute(string field) { this.field = field; } private string field; public string Field { get { return field; } }}
我已经定义了一个自定义属性
[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. } 我错过了什么? 解决方法
错字:应该是typeof(FieldAttribute).有一个不相关的系统枚举叫做FieldAttributes(在System.Reflection中,你在using指令中有,因为PropertyInfo正确解析).
此外,这更容易使用(假设该属性不允许重复): var field = (FieldAttribute) Attribute.GetCustomAttribute( property,typeof (FieldAttribute),false); if(field != null) { Console.WriteLine(field.Field); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |