속성을 작성하고 보안을 수행하는 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");
};
}
}
이제 예외를 throw하도록 코드를 가져올 수 있습니다. 그러나 그것은 당신이 메서드 자체를 호출하지 못하게합니까? –
나는 Attributes에서 어떤 행동을하는 것이 틀리다는데 동의합니다. 하지만 위의 코드에서 예외가 발생하지 않는 이유는 질문에 대한 답입니다. 속성 클래스의 인스턴스는 액세스하려고 할 때 만들어지기 때문입니다. –