2010-03-18 5 views
5

J'ai créé un attribut, appelez MyAttribute, qui effectue une certaine sécurité et, pour une raison quelconque, le constructeur n'est pas renvoyé, pourquoi?Classe d'attribut n'appelant pas le constructeur

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"); 
     }; 
    } 
} 

Répondre

1

En fait, il échoue, mais seulement si vous essayez d'obtenir des propriétés d'attribut. Voici un exemple qui échoue:

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

Alors maintenant vous pouvez obtenir votre code pour lancer une exception. Mais cela vous empêche-t-il d'appeler la méthode elle-même? –

+0

Je suis d'accord qu'il est faux d'avoir un comportement dans les attributs. Mais la question était pourquoi l'exception ne se produit pas dans le code ci-dessus et la réponse est - parce que l'instance de la classe d'attribut est créée lorsque vous essayez d'y accéder. –

8

Les attributs sont appliqués au moment de la compilation et les constructeurs sont utilisés uniquement pour remplir les propriétés. Les attributs sont des métadonnées et ne peuvent être examinés qu'à l'exécution.

En fait, les attributs ne doivent contenir aucun comportement.

+0

Si tel est le cas, comment définir la sécurité d'une méthode? – Coppermill

+0

C'est un sujet complètement différent, mais vous voudrez peut-être jeter un oeil à Code Access Security. –

+0

Je ne recommanderais pas CAS car il est très complexe de se tromper et a été abandonné dans .Net 4.0. – adrianbanks

Questions connexes