C# GetCustomAttributes不返回值
我已经定义了一个自定义属性C# GetCustomAttributes不返回值,c#,reflection,ado.net,C#,Reflection,Ado.net,我已经定义了一个自定义属性 [AttributeUsage(AttributeTargets.Property )] public class FieldAttribute: Attribute { public FieldAttribute(string field) { this.field = field; } private string field; public string Field { get {
[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.
}
typeOfT=typeof(T);
T obj=Activator.CreateInstance();
PropertyInfo[]propInfo=typeOfT.GetProperties();
foreach(PropertyInfo中的PropertyInfo属性)
{
object[]colName=roperty.GetCustomAttributes(typeof(FieldAttributes),false);
///colName没有值。
}
我遗漏了什么?打字:应该是
typeof(FieldAttribute)
。有一个不相关的系统枚举名为FieldAttributes
(在system.Reflection
中,由于PropertyInfo
正确解析,因此您在中使用了指令
此外,这更易于使用(假设属性不允许重复):
FieldAttributes
是打字错误吗?应该是FieldAttribute
?roperty
也是一个拼写错误吗?还有-你用什么来称呼它呢?是的,拼写错误。使用更好的名称,例如ColumnNameAttribute。或者只使用LINQtoSQL,它做完全相同的事情。
var field = (FieldAttribute) Attribute.GetCustomAttribute(
property, typeof (FieldAttribute), false);
if(field != null) {
Console.WriteLine(field.Field);
}