【问题标题】:Attribute class dont work [duplicate]属性类不起作用[重复]
【发布时间】:2013-06-26 19:53:37
【问题描述】:

我有这个简单的程序,问题是代码永远不会到达 TestClassAttribute 类。控制台输出为:

init
executed
end

代码

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("init");
        var test = new Test();
        test.foo();
        Console.WriteLine("end");
        Console.ReadKey();
    }
    public class TestClassAttribute : Attribute
    {
        public TestClassAttribute()
        {
            Console.WriteLine("AttrClass");
            Console.WriteLine("I am here. I'm the attribute constructor!");
            Console.ReadLine();
        }
    }

    public class Test
    {
        [TestClass]
        public void foo()
        {
            Console.WriteLine("executed");
        }
    }
}

【问题讨论】:

  • 你永远不会构造 TestClassAttribute 的实例,例如new TestClassAttribute().

标签: c# attributes


【解决方案1】:

您可能应该阅读How do attribute classes work?

当您创建应用它们的对象时,它们不会被实例化,不是一个静态实例,不是每个对象实例 1 个。他们也没有访问他们所应用的类..

您可以尝试获取类、方法、属性等的属性列表。当您获得这些属性的列表时 - 这就是它们将被实例化的地方。然后您可以对这些属性中的数据进行操作。

【讨论】:

    【解决方案2】:

    属性本身不会做任何事情。它们甚至在一个要求特定类/方法的属性之前构建。

    因此,要让您的代码编写“AttrClass”,您需要明确要求foo 方法的属性。

    【讨论】:

      【解决方案3】:

      属性被延迟实例化。您必须获取属性才能调用构造函数。

      var attr = test.GetType().GetMethod("foo")
                  .GetCustomAttributes(typeof(TestClassAttribute), false)
                  .FirstOrDefault();
      

      【讨论】:

        【解决方案4】:

        不,不。属性是特殊的。在您使用反射来获取它们之前,它们的构造函数不会运行。然后他们就需要运行了。比如这个小方法反映到属性中:

        public static string RunAttributeConstructor<TType>(TType value)
        {
            Type type = value.GetType();
            var attributes = type.GetCustomAttributes(typeof(TestClassAttribute), false);
        }
        

        您会看到在 Main 中调用它的任何位置都会运行该属性的构造函数。

        【讨论】:

          猜你喜欢
          • 2018-07-05
          • 1970-01-01
          • 2017-03-04
          • 2015-04-28
          • 2014-08-07
          • 1970-01-01
          • 2014-02-22
          • 2018-06-22
          • 2019-08-29
          相关资源
          最近更新 更多