属性类不调用构造函数

我创建了一个属性,调用MyAttribute,它正在执行某些安全性,并且由于某种原因,构造函数没有被触发,任何原因?

public class Driver { // Entry point of the program public static void Main(string[] Args) { Console.WriteLine(SayHello1("Hello to Me 1")); Console.WriteLine(SayHello2("Hello to Me 2")); Console.ReadLine(); } [MyAttribute("hello")] public static string SayHello1(string str) { return str; } [MyAttribute("Wrong Key, should fail")] public static string SayHello2(string str) { return str; } } [AttributeUsage(AttributeTargets.Method)] public class MyAttribute : Attribute { public MyAttribute(string VRegKey) { if (VRegKey == "hello") { Console.WriteLine("Aha! You're Registered"); } else { throw new Exception("Oho! You're not Registered"); }; } } 

实际上它失败了,但只有当你试图获得属性属性时。 这是一个失败的例子:

 using System; public class Driver { // Entry point of the program public static void Main(string[] Args) { Console.WriteLine(SayHello1("Hello to Me 1")); Console.WriteLine(SayHello2("Hello to Me 2")); Func action1 = SayHello1; Func action2 = SayHello2; MyAttribute myAttribute1 = (MyAttribute)Attribute.GetCustomAttribute(action1.Method, typeof(MyAttribute)); MyAttribute myAttribute2 = (MyAttribute)Attribute.GetCustomAttribute(action2.Method, typeof(MyAttribute)); Console.ReadLine(); } [MyAttribute("hello")] public static string SayHello1(string str) { return str; } [MyAttribute("Wrong Key, should fail")] public static string SayHello2(string str) { return str; } } [AttributeUsage(AttributeTargets.Method)] public class MyAttribute : Attribute { public string MyProperty { get; set; } public string MyProperty2 { get; set; } public MyAttribute(string VRegKey) { MyProperty = VRegKey; if (VRegKey == "hello") { Console.WriteLine("Aha! You're Registered"); } else { throw new Exception("Oho! You're not Registered"); }; MyProperty2 = VRegKey; } } 

属性在编译时应用,构造函数仅用于填充属性。 属性是元数据,只能在运行时检查。

实际上,Attributes根本不应包含任何行为。