0

I would expect there to be three lines of output from this code, but there are none:

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

Am I missing soemthing obvious?

Andrew

amaca
  • 1,410
  • 13
  • 17
  • Check out this question: http://stackoverflow.com/questions/2281972/c-reflection-how-to-get-a-list-of-properties-with-a-given-attribute – wsanville Mar 06 '11 at 17:28

2 Answers2

3

t.GetCustomAttributes returns the attributes declared on the class itself.

You need to loop through t.GetProperties() and call GetCustomAttributes on the individual PropertyInfos.

SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
2

Try something like this in the Main method:

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());
}
rsbarro
  • 26,421
  • 8
  • 69
  • 74