CustomAttributes的行为不符合预期

时间:2011-03-06 17:25:21

标签: c#

我希望这段代码有三行输出,但没有:

[AttributeUsage( AttributeTargets.Property )]
public class FieldAttribute : System.Attribute
{
  public String FieldName
  {
    get;
    set;
  }
}

public class Host
{

  [Field]
  public String FieldOne
  {
    get;
    set;
  }

  [Field(FieldName="Foo")]
  public String FieldTwo
  {
    get;
    set;
  }

  [FieldAttribute]
  public String FieldThree
  {
    get;
    set;
  }

  public String FieldFour
  {
    get;
    set;
  }
}


class Program
{
  static void Main( string[] args )
  {
    Type t = typeof(Host);
    foreach ( Object att in t.GetCustomAttributes( typeof(FieldAttribute), true ) )
    {
      Console.WriteLine( att.ToString() );
    }
  }
}

我错过了那么明显吗?

安德鲁

2 个答案:

答案 0 :(得分:3)

t.GetCustomAttributes返回类本身声明的属性。

您需要循环浏览t.GetProperties()并致电GetCustomAttributes个人PropertyInfo

答案 1 :(得分:2)

在Main方法中尝试这样的事情:

Type t = typeof(Host);
foreach(var prop in t.GetProperties())
{
    var attrs = prop.GetCustomAttributes(typeof(FieldAttribute), true);
    foreach(var attr in attrs)
        Console.WriteLine("{0} - {1}", prop.Name, attr.ToString());
}