属性类不起作用

本文关键字:不起作用 属性 | 更新日期: 2023-09-27 18:20:05

我有一个简单的程序,问题是代码永远不会到达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");
        }
    }
}

属性类不起作用

您可能应该阅读属性类是如何工作的?。

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

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

属性本身不做任何事情。在请求特定类/方法的属性之前,它们甚至没有构造

因此,为了让代码编写"AttrClass",您需要显式地请求foo方法的属性。

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

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

否,否。属性是特殊的。它们的构造函数只有在使用反射才能运行。他们不需要运行。例如,这个小方法反映到属性中:

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

Main中,无论在哪里调用它,都将运行该属性的构造函数。