我有这个简单的程序,问题是代码永远不会到达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");
}
}
}
答案 0 :(得分:3)
您应该阅读How do attribute classes work?。
当您创建应用它们的对象时,它们不会被实例化,而不是一个静态实例,而不是每个对象实例1。他们也没有访问他们应用的类..
您可以尝试获取类,方法,属性等的属性列表。当您获得这些属性的列表时 - 这是它们将被实例化的位置。然后,您可以对这些属性中的数据进行操作。
答案 1 :(得分:2)
属性本身不做任何事情。在之前,它们甚至没有构造,因为它要求特定类/方法的属性。
因此,要让您的代码编写“AttrClass”,您需要明确地询问foo
方法的属性。
答案 2 :(得分:1)
属性被懒惰地实例化。您必须获取属性才能调用构造函数。
var attr = test.GetType().GetMethod("foo")
.GetCustomAttributes(typeof(TestClassAttribute), false)
.FirstOrDefault();
答案 3 :(得分:0)
不,不。属性为特殊。他们的构造函数在你使用反射到达它们之前不会运行。他们不会需要来运行。例如,这个小方法反映在属性中:
public static string RunAttributeConstructor<TType>(TType value)
{
Type type = value.GetType();
var attributes = type.GetCustomAttributes(typeof(TestClassAttribute), false);
}
您将在Main
中看到您在此处调用此属性的位置,该属性的构造函数将会运行。