Switch Clase

Definición

Proporciona una clase base abstracta para crear nuevos modificadores de depuración y traza.

public ref class Switch abstract
public abstract class Switch
type Switch = class
Public MustInherit Class Switch
Herencia
Switch
Derivado

Ejemplos

En el ejemplo siguiente se muestra cómo definir una nueva Switch clase con cuatro niveles de seguimiento que se pueden usar para realizar un seguimiento de una pila de llamadas. Puede usar el modificador para instrumentar la aplicación para registrar cada vez que se introduce o sale el método.

En el primer ejemplo se crea la enumeración utilizada para establecer el nivel del modificador.

// The following are possible values for the new switch.
public enum class MethodTracingSwitchLevel
{
    Off = 0,
    EnteringMethod = 1,
    ExitingMethod = 2,
    Both = 3
};
// The following are possible values for the new switch.
public enum MethodTracingSwitchLevel
{
    Off = 0,
    EnteringMethod = 1,
    ExitingMethod = 2,
    Both = 3,
}
' The following are possible values for the new switch.
Public Enum MethodTracingSwitchLevel
    Off = 0
    EnteringMethod = 1
    ExitingMethod = 2
    Both = 3
End Enum 'MethodTracingSwitchLevel

En el ejemplo siguiente se crea el nuevo modificador. El código implementa una Level propiedad para establecer el valor del nuevo modificador. Level llama a la propiedad SwitchSetting protegida que asigna el valor al nuevo modificador. En este ejemplo también se implementan dos propiedades de evaluador para obtener el valor asignado del modificador.

public ref class MyMethodTracingSwitch: public Switch
{
protected:
    bool outExit;
    bool outEnter;
    MethodTracingSwitchLevel level;

public:
    MyMethodTracingSwitch( String^ displayName, String^ description )
       : Switch( displayName, description )
    {}

    property MethodTracingSwitchLevel Level
    {
        MethodTracingSwitchLevel get()
        {
            return level;
        }

       void set( MethodTracingSwitchLevel value )
       {
           SetSwitchSetting( (int)value );
       }
    }

protected:
    void SetSwitchSetting( int value )
    {
        if ( value < 0 )
        {
            value = 0;
        }

        if ( value > 3 )
        {
            value = 3;
        }

        level = (MethodTracingSwitchLevel)value;
        outEnter = false;
        if ((value == (int)MethodTracingSwitchLevel::EnteringMethod) ||
            (value == (int)MethodTracingSwitchLevel::Both))
        {
            outEnter = true;
        }

        outExit = false;
        if ((value == (int)MethodTracingSwitchLevel::ExitingMethod) ||
            (value == (int)MethodTracingSwitchLevel::Both))
        {
            outExit = true;
        }
    }

public:
    property bool OutputExit
    {
        bool get()
        {
            return outExit;
        }
    }

    property bool OutputEnter
    {
        bool get()
        {
            return outEnter;
        }
    }
};
public class MyMethodTracingSwitch : Switch
{
    protected bool outExit;
    protected bool outEnter;
    protected MethodTracingSwitchLevel level;

    public MyMethodTracingSwitch(string displayName, string description) :
        base(displayName, description)
    {
    }

    public MethodTracingSwitchLevel Level
    {
        get
        {
            return level;
        }
        set
        {
            SetSwitchSetting((int)value);
        }
    }

    protected void SetSwitchSetting(int value)
    {
        if (value < 0)
        {
            value = 0;
        }
        if (value > 3)
        {
            value = 3;
        }

        level = (MethodTracingSwitchLevel)value;

        outEnter = false;
        if ((value == (int)MethodTracingSwitchLevel.EnteringMethod) ||
            (value == (int)MethodTracingSwitchLevel.Both))
        {
            outEnter = true;
        }

        outExit = false;
        if ((value == (int)MethodTracingSwitchLevel.ExitingMethod) ||
            (value == (int)MethodTracingSwitchLevel.Both))
        {
            outExit = true;
        }
    }

    public bool OutputExit
    {
        get
        {
            return outExit;
        }
    }

    public bool OutputEnter
    {
        get
        {
            return outEnter;
        }
    }
}
Public Class MyMethodTracingSwitch
    Inherits Switch
    Protected outExit As Boolean
    Protected outEnter As Boolean
    Protected myLevel As MethodTracingSwitchLevel
    
    Public Sub New(displayName As String, description As String)
        MyBase.New(displayName, description)
    End Sub


    Public Property Level() As MethodTracingSwitchLevel
        Get
            Return myLevel
        End Get
        Set
            SetSwitchSetting(CInt(value))
        End Set
    End Property


    Protected Sub SetSwitchSetting(value As Integer)
        If value < 0 Then
            value = 0
        End If
        If value > 3 Then
            value = 3
        End If

        myLevel = CType(value, MethodTracingSwitchLevel)

        outEnter = False
        If value = CInt(MethodTracingSwitchLevel.EnteringMethod) Or _
            value = CInt(MethodTracingSwitchLevel.Both) Then

            outEnter = True
        End If

        outExit = False
        If value = CInt(MethodTracingSwitchLevel.ExitingMethod) Or _
            value = CInt(MethodTracingSwitchLevel.Both) Then

            outExit = True
        End If
    End Sub


    Public ReadOnly Property OutputExit() As Boolean
        Get
            Return outExit
        End Get
    End Property


    Public ReadOnly Property OutputEnter() As Boolean
        Get
            Return outEnter
        End Get
    End Property
End Class

En el ejemplo siguiente se crea un nuevo modificador en Main. Crea un nuevo modificador y le asigna un valor. A continuación, dependiendo de la configuración del conmutador, genera mensajes de depuración para escribir y salir del método.

public ref class Class1
{
private:

    /* Create an instance of MyMethodTracingSwitch.*/
    static MyMethodTracingSwitch^ mySwitch =
        gcnew MyMethodTracingSwitch( "Methods","Trace entering and exiting method" );

public:
    static void main()
    {
        // Add the console listener to see trace messages as console output
        Trace::Listeners->Add(gcnew ConsoleTraceListener(true));
        Debug::AutoFlush = true;

        // Set the switch level to both enter and exit
        mySwitch->Level = MethodTracingSwitchLevel::Both;

        // Write a diagnostic message if the switch is set to entering.
        Debug::WriteLineIf(mySwitch->OutputEnter, "Entering Main");

        // Insert code to handle processing here...

        // Write another diagnostic message if the switch is set to exiting.
        Debug::WriteLineIf(mySwitch->OutputExit, "Exiting Main");
    }
};
public class Class1
{
    /* Create an instance of MyMethodTracingSwitch.*/
    static MyMethodTracingSwitch mySwitch =
        new MyMethodTracingSwitch("Methods", "Trace entering and exiting method");

    public static void Main()
    {
        // Add the console listener to see trace messages as console output
        Trace.Listeners.Add(new ConsoleTraceListener(true));
        Debug.AutoFlush = true;

        // Set the switch level to both enter and exit
        mySwitch.Level = MethodTracingSwitchLevel.Both;

        // Write a diagnostic message if the switch is set to entering.
        Debug.WriteLineIf(mySwitch.OutputEnter, "Entering Main");

        // Insert code to handle processing here...

        // Write another diagnostic message if the switch is set to exiting.
        Debug.WriteLineIf(mySwitch.OutputExit, "Exiting Main");
    }
}
Public Class Class1
    ' Create an instance of MyMethodTracingSwitch.
    Private Shared mySwitch As New _
        MyMethodTracingSwitch("Methods", "Trace entering and exiting method")

    Public Shared Sub Main()
        ' Add the console listener to see trace messages as console output
        Trace.Listeners.Add(New ConsoleTraceListener(True))
        Debug.AutoFlush = True

        ' Set the switch level to both enter and exit
        mySwitch.Level = MethodTracingSwitchLevel.Both

        ' Write a diagnostic message if the switch is set to entering.
        Debug.WriteLineIf(mySwitch.OutputEnter, "Entering Main")

        ' Insert code to handle processing here...

        ' Write another diagnostic message if the switch is set to exiting.
        Debug.WriteLineIf(mySwitch.OutputExit, "Exiting Main")
    End Sub
End Class

Comentarios

Un modificador proporciona un mecanismo eficaz para controlar la salida de seguimiento y depuración en tiempo de ejecución mediante la configuración externa. La Switch clase implementa el comportamiento predeterminado de los modificadores, lo que le permite cambiar el nivel de conmutador en tiempo de ejecución.

Esta clase es la clase base para las BooleanSwitchclases , SourceSwitchy TraceSwitch . Estos modificadores satisfacen la mayoría de las necesidades de depuración y seguimiento. Para obtener más información sobre los modificadores de seguimiento, vea Modificadores de seguimiento.

Debe habilitar el seguimiento o la depuración para usar un modificador. La siguiente sintaxis es específica del compilador. Si usa compiladores distintos de C# o Visual Basic, consulte la documentación del compilador.

  • Para habilitar la depuración en C#, agregue la /d:DEBUG marca a la línea de comandos del compilador al compilar el código, o bien puede agregarla #define DEBUG a la parte superior del archivo. En Visual Basic, agregue la /d:DEBUG=True marca a la línea de comandos del compilador.

  • Para habilitar el seguimiento mediante en C#, agregue la /d:TRACE marca a la línea de comandos del compilador al compilar el código o agregue #define TRACE a la parte superior del archivo. En Visual Basic, agregue la /d:TRACE=True marca a la línea de comandos del compilador.

Para establecer el nivel del modificador en una aplicación de .NET Framework, edite el archivo de configuración que corresponde al nombre de la aplicación. Dentro de este archivo, puede agregar un modificador y establecer su valor, quitar un modificador o borrar todos los modificadores establecidos previamente por la aplicación. El archivo de configuración debe tener formato similar al ejemplo siguiente:

<configuration>  
  <system.diagnostics>  
    <switches>  
      <add name="mySwitch" value="true" />  
    </switches>  
  </system.diagnostics>  
</configuration>  

En esta sección de configuración de ejemplo se define un BooleanSwitch con la DisplayName propiedad establecida mySwitch en y el Enabled valor establecido en true. En la aplicación, puede usar el valor del modificador configurado mediante la creación de un BooleanSwitch con el mismo nombre, como se muestra en el ejemplo de código siguiente.

private:
    static BooleanSwitch^ boolSwitch = gcnew BooleanSwitch("mySwitch",
        "Switch in config file");

public:
    static void Main( )
    {
        //...
        Console::WriteLine("Boolean switch {0} configured as {1}",
            boolSwitch->DisplayName, ((Boolean^)boolSwitch->Enabled)->ToString());
        if (boolSwitch->Enabled)
        {
            //...
        }
    }
private static BooleanSwitch boolSwitch = new BooleanSwitch("mySwitch",
    "Switch in config file");

public static void Main()
{
    //...
    Console.WriteLine("Boolean switch {0} configured as {1}",
        boolSwitch.DisplayName, boolSwitch.Enabled.ToString());
    if (boolSwitch.Enabled)
    {
        //...
    }
}

Notas a los implementadores

Si necesita niveles de seguimiento o mecanismos para establecer niveles de modificador diferentes de los proporcionados por BooleanSwitchy SourceSwitch TraceSwitch, puede heredar de Switch. Al heredar de esta clase, debe implementar el SwitchSetting método .

Constructores

Switch(String, String)

Inicializa una nueva instancia de la clase Switch.

Switch(String, String, String)

Inicializa una nueva instancia de la clase Switch especificando el nombre para mostrar, la descripción y el valor predeterminado del modificador.

Propiedades

Attributes

Obtiene los atributos de modificador personalizados definidos en el archivo de configuración de la aplicación.

Description

Obtiene una descripción del modificador.

DisplayName

Obtiene el nombre utilizado para identificar el modificador.

SwitchSetting

Obtiene o establece la configuración actual de este modificador.

Value

Obtiene o establece el valor del modificador.

Métodos

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetSupportedAttributes()

Obtiene los atributos personalizados que admite el modificador.

GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnSwitchSettingChanged()

Se invoca cuando cambia la propiedad SwitchSetting.

OnValueChanged()

Se invoca cuando cambia la propiedad Value.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a

Consulte también