Reputation: 13
I working on .NET 2.0. Unfortunatelly i couldn't use a newer version. I try to wrote my owne Attribute providing a simple value.
[AttributeUsage(AttributeTargets.All)]
public class testAttribute : Attribute
{
int b;
public testAttribute(int a)
{
b = a;
Console.WriteLine("Creating Attribute");
}
public testAttribute()
{
b = 5;
Console.WriteLine("Creating Attribute");
}
}
public class MyTestClass
{
[testAttribute]
public MyTestClass()
{
int a = 0;
Console.WriteLine("creating serializer 2");
}
[testAttribute(2)]
public void foo(){
//Type t = this.GetType();
//testAttribute[] t2 = (testAttribute[])t.GetCustomAttributes(typeof(testAttribute), true);
Console.WriteLine("calling foo");
object[] attr = typeof(MyTestClass).GetCustomAttributes(true);
int a = 5;
}
}
But that doesn't seem to work. I figured out that example from msdn [ http://msdn.microsoft.com/en-us/library/a4a92379%28v=vs.80%29.aspx ] and for me this looks very similar.
I also found this: Attribute on method doesn't work but this is not exactly my problem I think. As you can see I tried out the recommendation from BrokenGlass but I got an array with dimenson 0 that means there is no Attribute.
Any Suggestions? Regards Chomp
Upvotes: 1
Views: 94
Reputation: 190915
You have to call GetCustomAttributes
for the methods, not the type.
object[] attr = typeof(MyTestClass).GetMethod("foo").GetCustomAttributes(true);
Upvotes: 2