2010-03-18 6 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

Итак, теперь вы можете получить код для исключения. Но препятствует ли вам самому называть этот метод? –

+0

Я согласен с тем, что неправильное поведение в атрибутах. Но вопрос в том, почему исключение не происходит в приведенном выше коде, а ответ - потому что экземпляр класса атрибута создается при попытке получить к нему доступ. –

8

Атрибуты применяются во время компиляции, а конструкторы используются только для заполнения свойств. Атрибуты являются метаданными и могут быть проверены только во время выполнения.

Фактически, Атрибуты не должны содержать никакого поведения вообще.

+0

Если это так, как еще можно установить безопасность метода? – Coppermill

+0

Это совершенно другая тема, но вы можете взглянуть на Code Access Security. –

+0

Я бы не рекомендовал CAS, так как очень сложно получить право и устарело в .Net 4.0. – adrianbanks