我在研究.NET 2.0。不幸的是,我无法使用更新的版本。 我尝试编写我的owne属性,提供一个简单的值。
[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;
}
}
但这似乎不起作用。 我从msdn [http://msdn.microsoft.com/en-us/library/a4a92379%28v=vs.80%29.aspx]中找到了这个例子,对我而言,这看起来非常相似。
我也发现了这个:Attribute on method doesn't work但我认为这不是我的问题。正如你所看到的,我尝试了BrokenGlass的推荐,但是我得到了一个维度为0的数组,这意味着没有属性。
有什么建议吗? 问候Chomp
答案 0 :(得分:2)
您必须为方法调用GetCustomAttributes
,而不是类型。
object[] attr = typeof(MyTestClass).GetMethod("foo").GetCustomAttributes(true);