Share via


TraceSwitch Construtores

Definição

Inicializa uma nova instância da classe TraceSwitch.

Sobrecargas

TraceSwitch(String, String)

Inicializa uma nova instância da classe TraceSwitch usando o nome de exibição e a descrição especificados.

TraceSwitch(String, String, String)

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

TraceSwitch(String, String)

Origem:
TraceSwitch.cs
Origem:
TraceSwitch.cs
Origem:
TraceSwitch.cs

Inicializa uma nova instância da classe TraceSwitch usando o nome de exibição e a descrição especificados.

public:
 TraceSwitch(System::String ^ displayName, System::String ^ description);
public TraceSwitch (string displayName, string? description);
public TraceSwitch (string displayName, string description);
new System.Diagnostics.TraceSwitch : string * string -> System.Diagnostics.TraceSwitch
Public Sub New (displayName As String, description As String)

Parâmetros

displayName
String

O nome a ser exibido em uma interface do usuário.

description
String

A descrição do comutador.

Exemplos

O exemplo de código a seguir cria um novo TraceSwitch e usa a opção para determinar se as mensagens de erro devem ser impressas. A opção é criada no nível da classe. MyMethod gravará a primeira mensagem de erro se a Level propriedade estiver definida como TraceLevel.Error ou superior. No entanto, MyMethod não gravará a segunda mensagem de erro se for Level menor que TraceLevel.Verbose.

   // Class-level declaration.
   /* Create a TraceSwitch to use in the entire application.*/
private:
   static TraceSwitch^ mySwitch = gcnew TraceSwitch( "General", "Entire Application" );

public:
   static void MyMethod()
   {
      // Write the message if the TraceSwitch level is set to Error or higher.
      if ( mySwitch->TraceError )
         Console::WriteLine( "My error message." );
      
      // Write the message if the TraceSwitch level is set to Verbose.
      if ( mySwitch->TraceVerbose )
         Console::WriteLine( "My second error message." );
   }

   static void main()
   {
      // Run the method that prints error messages based on the switch level.
      MyMethod();
   }
//Class-level declaration.
/* Create a TraceSwitch to use in the entire application.*/
static TraceSwitch mySwitch = new TraceSwitch("General", "Entire Application");

static public void MyMethod()
{
    // Write the message if the TraceSwitch level is set to Error or higher.
    if (mySwitch.TraceError)
        Console.WriteLine("My error message.");

    // Write the message if the TraceSwitch level is set to Verbose.
    if (mySwitch.TraceVerbose)
        Console.WriteLine("My second error message.");
}

public static void Main(string[] args)
{
    // Run the method that prints error messages based on the switch level.
    MyMethod();
}
' Class-level declaration.
' Create a TraceSwitch to use in the entire application. 
Private Shared mySwitch As New TraceSwitch("General", "Entire Application")    

Public Shared Sub MyMethod()
    ' Write the message if the TraceSwitch level is set to Error or higher.
    If mySwitch.TraceError Then
        Console.WriteLine("My error message.")
    End If 
    ' Write the message if the TraceSwitch level is set to Verbose.
    If mySwitch.TraceVerbose Then
        Console.WriteLine("My second error message.")
    End If
End Sub

Public Shared Sub Main()
    ' Run the method that prints error messages based on the switch level.
    MyMethod()
End Sub

Comentários

Para .NET Framework aplicativos, para definir o nível do seu TraceSwitch, 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 uma opção ou limpar todas as opções definidas anteriormente pelo aplicativo. O arquivo de configuração deve ser formatado como o exemplo a seguir:

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

Você também pode usar texto para especificar o valor de uma opção. Por exemplo, true para um BooleanSwitch ou o texto que representa um valor de enumeração, como Error para um TraceSwitch. A linha <add name="mySwitch" value="Error" /> é equivalente a <add name="mySwitch" value="1" />.

Em seu aplicativo, você pode usar o nível de comutador configurado criando um TraceSwitch com o mesmo nome, conforme mostrado no exemplo a seguir:

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

public:
    static void Main(array<String^>^ args)
    {
        //...
        Console::WriteLine("Trace switch {0} configured as {1}",
        appSwitch->DisplayName, appSwitch->Level.ToString());
        if (appSwitch->TraceError)
        {
            //...
        }
    }
private static TraceSwitch appSwitch = new TraceSwitch("mySwitch",
    "Switch in config file");

public static void Main(string[] args)
{
    //...
    Console.WriteLine("Trace switch {0} configured as {1}",
    appSwitch.DisplayName, appSwitch.Level.ToString());
    if (appSwitch.TraceError)
    {
        //...
    }
}
Private Shared appSwitch As new TraceSwitch("mySwitch", _
    "Switch in config file")

Public Shared Sub Main(args As String())
    '...
    Console.WriteLine("Trace switch {0} configured as {1}",
    appSwitch.DisplayName, appSwitch.Level.ToString())
    If appSwitch.TraceError = True  Then
        '...
    End If
End Sub

Esse construtor define a Level propriedade do novo comutador como TraceLevel.Off. Ou, para aplicativos .NET Framework, as configurações de comutador são obtidas do arquivo de configuração, se disponíveis.

A TraceSwitch classe fornece as TraceErrorpropriedades , TraceWarning, TraceInfoe TraceVerbose para testar o Level da opção. A Level propriedade obtém ou define o do TraceLevelcomutador.

Observação

Para melhorar o desempenho, você pode criar TraceSwitch membros static em sua classe.

Confira também

Aplica-se a

TraceSwitch(String, String, String)

Origem:
TraceSwitch.cs
Origem:
TraceSwitch.cs
Origem:
TraceSwitch.cs

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

public:
 TraceSwitch(System::String ^ displayName, System::String ^ description, System::String ^ defaultSwitchValue);
public TraceSwitch (string displayName, string? description, string defaultSwitchValue);
public TraceSwitch (string displayName, string description, string defaultSwitchValue);
new System.Diagnostics.TraceSwitch : string * string * string -> System.Diagnostics.TraceSwitch
Public Sub New (displayName As String, description As String, defaultSwitchValue As String)

Parâmetros

displayName
String

O nome a ser exibido em uma interface do usuário.

description
String

A descrição do comutador.

defaultSwitchValue
String

O valor padrão do comutador.

Comentários

O displayName parâmetro é usado para definir o valor da DisplayName propriedade, o description parâmetro é usado para definir o valor da Description propriedade e o defaultSwitchValue parâmetro é salvo como um campo e usado para inicializar a Value propriedade na primeira referência. Consulte o TraceSwitch(String, String) construtor para obter mais informações e um exemplo de código.

Aplica-se a