use*_*322 6 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 { return field; }
}
}
Run Code Online (Sandbox Code Playgroud)
我的使用自定义属性的类如下所示
[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; }
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试获取自定义属性的值时,它返回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.
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
错字:应该是typeof(FieldAttribute).有一个不相关的系统枚举被调用FieldAttributes(in System.Reflection,你在你的using指令中,因为PropertyInfo正确解析).
此外,这更容易使用(假设该属性不允许重复):
var field = (FieldAttribute) Attribute.GetCustomAttribute(
property, typeof (FieldAttribute), false);
if(field != null) {
Console.WriteLine(field.Field);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4669 次 |
| 最近记录: |