【问题标题】:C# CustomAttribute wouldn't workC# CustomAttribute 不起作用
【发布时间】:2013-03-21 19:05:10
【问题描述】:

我在 .NET 2.0 上工作。不幸的是,我无法使用更新的版本。 我尝试编写自己的属性来提供一个简单的值。

[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 的数组,这意味着没有属性。

有什么建议吗? 问候乔普

【问题讨论】:

  • 什么是“不起作用”?

标签: c# .net custom-attributes


【解决方案1】:

您必须为方法而不是类型调用GetCustomAttributes

object[] attr = typeof(MyTestClass).GetMethod("foo").GetCustomAttributes(true);

【讨论】:

  • 考虑使用GetConstructor() 作为第一个。方法名称也区分大小写。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
  • 2015-05-29
  • 2015-06-29
  • 2018-05-14
相关资源
最近更新 更多