Switch Classe

Definição

Fornece uma classe base abstrata para criar novos comutadores de rastreamento e depuração.

public ref class Switch abstract
public abstract class Switch
type Switch = class
Public MustInherit Class Switch
Herança
Switch
Derivado

Exemplos

O exemplo a seguir mostra como definir uma nova Switch classe com quatro níveis de rastreamento que podem ser usados para rastrear uma pilha de chamadas. Você pode usar a opção para instrumentar seu aplicativo para fazer logon sempre que o método for inserido ou encerrado.

O primeiro exemplo cria a enumeração usada para definir o nível do comutador.

// 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

O exemplo a seguir cria a nova opção. O código implementa uma Level propriedade para definir o valor da nova opção. Level chama a propriedade SwitchSetting protegida que atribui o valor à nova opção. Este exemplo também implementa duas propriedades de assessor para obter o valor atribuído da opção.

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

O exemplo a seguir cria uma nova opção em Main. Ele cria uma nova opção e atribui-lhe um valor. Em seguida, dependendo das configurações de comutador, ele gera mensagens de depuração para inserir e sair do 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

Comentários

Uma opção fornece um mecanismo eficiente para controlar a saída de rastreamento e depuração em tempo de execução usando configurações externas. A Switch classe implementa o comportamento padrão para comutadores, permitindo que você altere o nível de comutador em tempo de execução.

Essa classe é a classe base para o BooleanSwitch, SourceSwitche TraceSwitch classes. Esses comutadores atendem à maioria das necessidades de depuração e rastreamento. Para obter mais informações sobre os comutadores de rastreamento, consulte Os Comutadores de Rastreamento.

Você deve habilitar o rastreamento ou a depuração para usar um comutador. A sintaxe a seguir é específica do compilador. Se você usar compiladores diferentes de C# ou Visual Basic, consulte a documentação do compilador.

  • Para habilitar a depuração em C#, adicione o /d:DEBUG sinalizador à linha de comando do compilador quando você compilar seu código ou pode adicionar #define DEBUG à parte superior do arquivo. Em Visual Basic, adicione o /d:DEBUG=True sinalizador à linha de comando do compilador.

  • Para habilitar o rastreamento usando em C#, adicione o /d:TRACE sinalizador à linha de comando do compilador ao compilar seu código ou adicione #define TRACE à parte superior do arquivo. Em Visual Basic, adicione o /d:TRACE=True sinalizador à linha de comando do compilador.

Para definir o nível da opção em um aplicativo .NET Framework, edite o arquivo de configuração que corresponde ao nome do aplicativo. Nesse arquivo, você pode adicionar uma opção e definir seu valor, remover um comutador ou limpar todos os comutadores definidos anteriormente pelo aplicativo. O arquivo de configuração deve ser formatado como o exemplo a seguir:

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

Esta seção de configuração de exemplo define um BooleanSwitch com a DisplayName propriedade definida mySwitch como e o Enabled valor definido como true. Em seu aplicativo, você pode usar o valor de comutador configurado criando um BooleanSwitch com o mesmo nome, conforme mostrado no exemplo de código a seguir.

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 aos Implementadores

Se você precisar de níveis de rastreamento ou mecanismos para definir níveis de comutador diferentes daqueles fornecidos por BooleanSwitch, SourceSwitch e TraceSwitch, você pode herdar de Switch. Ao herdar dessa classe, você deve implementar o SwitchSetting método.

Construtores

Switch(String, String)

Inicializa uma nova instância da classe Switch.

Switch(String, String, String)

Inicializa uma nova instância da classe Switch, especificando o nome de exibição, a descrição e o valor padrão para o comutador.

Propriedades

Attributes

Obtém os atributos de opção personalizados definidos no arquivo de configuração de aplicativo.

Description

Obtém uma descrição do comutador.

DisplayName

Obtém o nome usado para identificar o comutador.

SwitchSetting

Obtém ou define a configuração atual para essa opção.

Value

Obtém ou define o valor da opção.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetSupportedAttributes()

Obtém os atributos personalizados com suporte do comutador.

GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
OnSwitchSettingChanged()

Invocado quando a propriedade SwitchSetting é alterada.

OnValueChanged()

Invocado quando a propriedade Value é alterada.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Confira também