我已经创建了一个名为 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");
};
}
}
最佳答案
属性在编译时应用,构造函数仅用于填充属性。属性是元数据,只能在运行时检查。
事实上,属性根本不应该包含任何行为。
关于c# - 属性类不调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2470164/