Frage

We have this code:

public static class MyCLass 
{
    [Conditional("Debugging")]  
    public static void MyMethod()
    {
         Console.WriteLine("Example method");
    }
}
.
.
.
//In debug mode: Executing Main method in debug mode
MyClass.MyMethod()

All I want to know is how the Conditional Attribute could change the behavior of MyMethod, assuming that in .NET the Conditional attribute is defined as:

public class Conditional: Attribute
{
   .
   .
   public string Mode { get; set; )
   .
   .
   public Conditional(string Mode)
   {
       .
       .
       this.Mode = Mode;
       if (Mode == "Debugging")
       {
          #ifdef DEBUG
          //HOW THE CONDITIONAL CONSTRUCTOR COULD CHANGE THE BEHAVIOUR OF MyMethod
          #endif
       }
       .
       .
   }
}

How can I access the resources (methods, members, classes ..) that are decorated by my attribute (i.e. from MyAttribute class) ?

War es hilfreich?

Lösung

The attribute tells the compiler to see if the flag is set, so that if it's not, any call to that method will not be compiled, just as if the method call never existed in the code. You could easily see that by using a reflector tool such as ILSpy.

So in fact it's not that the attribute changes the behavior of the method, but the compiler which knows to look for that attribute and change its behavior accordingly.

The attributed method (MyMethod in your case) is still compiled and can be accessed via reflection.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top