2010-03-18 7 views
5

He creado un Atributo, llamo a MyAttribute, que está realizando alguna seguridad y por alguna razón el Constructor no se está disparando, ¿por qué?Clase de atributo que no llama al constructor

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

Respuesta

1

En realidad falla, pero solo si intenta obtener propiedades de atributo. Aquí hay un ejemplo que falla:

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

Ahora puede obtener su código para lanzar una excepción. Pero, ¿eso le impide llamar al método en sí? –

+0

Acepto que es incorrecto tener algún comportamiento en los Atributos. Pero la pregunta era por qué la excepción no ocurre en el código anterior y la respuesta es - porque la instancia de la clase de atributo se crea cuando intenta acceder a ella. –

8

Los atributos se aplican en tiempo de compilación y los constructores solo se usan para completar las propiedades. Los atributos son metadatos y solo pueden examinarse en tiempo de ejecución.

De hecho, los atributos no deben contener ningún tipo de comportamiento.

+0

Si este es el caso, ¿cómo se puede establecer la seguridad de un método? – Coppermill

+0

Ese es un tema completamente diferente, pero es posible que desee echar un vistazo a Seguridad de acceso de código. –

+0

No recomendaría CAS, ya que es muy complejo hacerlo bien y se ha desaprobado en .Net 4.0. – adrianbanks

Cuestiones relacionadas