2010-03-18 5 views
5

속성을 작성하고 보안을 수행하는 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"); 
     }; 
    } 
} 

답변

1

실제로 속성 속성을 얻으려는 경우에만 실패합니다. 다음은 실패한 예입니다.

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<string, string> action1 = SayHello1; 
     Func<string, string> 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; 
    } 
} 
+0

이제 예외를 throw하도록 코드를 가져올 수 있습니다. 그러나 그것은 당신이 메서드 자체를 호출하지 못하게합니까? –

+0

나는 Attributes에서 어떤 행동을하는 것이 틀리다는데 동의합니다. 하지만 위의 코드에서 예외가 발생하지 않는 이유는 질문에 대한 답입니다. 속성 클래스의 인스턴스는 액세스하려고 할 때 만들어지기 때문입니다. –

8

속성은 컴파일 타임에 적용되며 생성자는 속성을 채우는 용도로만 사용됩니다. 속성은 메타 데이터이며 런타임에만 검사 할 수 있습니다.

실제로 속성에는 아무런 동작이 없어야합니다.

+0

이 경우 다른 방법으로 보안을 설정하는 방법은 무엇입니까? – Coppermill

+0

이것은 완전히 다른 주제이지만 코드 액세스 보안을 살펴볼 수 있습니다. –

+0

CAS는 매우 복잡하고 .Net 4.0에서 사용되지 않으므로 CAS를 권장하지 않습니다. – adrianbanks

관련 문제