我已经创建了一个属性,调用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");
};
}
}
所以现在你可以让你的代码抛出异常。但这是否阻止你调用方法本身? – 2010-03-18 19:05:42
我同意在属性中有任何行为是错误的。但问题是,为什么异常不会在上面的代码发生,答案是 - 因为当你试图访问创建它的属性类的实例。 – 2010-03-18 19:21:57