c# - GetCustomAttributes 不返回值

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

    }
}

我的类使用自定义属性如下

[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.
}

我错过了什么?

最佳答案

打字错误:应为 typeof(FieldAttribute)。有一个不相关的系统枚举,称为 FieldAttributes(在 System.Reflection 中,您在 using 指令中有它,因为 PropertyInfo正确解析)。

此外,这更容易使用(假设属性不允许重复):

var field = (FieldAttribute) Attribute.GetCustomAttribute(
          property, typeof (FieldAttribute), false);
if(field != null) {
    Console.WriteLine(field.Field);
}

关于c# - GetCustomAttributes 不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10315637/

相关文章:

c# - 使用 DI 和 UoW 模式时是否需要使用 EF 语句

c# - 无法在带有输出参数的存储过程中将对象从 DBNull 转换为其他类型

c# - 将像素着色器应用于图像

.net - ParameterInfo.DefaultValue 和 ParameterInfo.RawDefaultValue 之间的区别

c# - 本地数据库插入查询不执行任何操作

c# - 解除阻止文件夹中的所有程序集文件

c# - .NET 反射 : determine sizes of a class' fields

reflection - 有没有一种简单(惯用)的方法将 java.lang.reflect.Method 转换为 Scala 函数?

c# - 带循环的sql事务,一条commit语句

sql-server - SQL Server 连接任意返回 233 或 18456 错误代码