Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# GetCustomAttributes不返回值_C#_Reflection_Ado.net - Fatal编程技术网

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);
}