Switch Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Fornece uma classe base abstrata para criar novas opções de depuração e rastreamento.
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 registrar em log sempre que o método for inserido ou encerrado.
O primeiro exemplo cria a enumeração usada para definir o nível da opção.
// 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 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 um valor a ela. Em seguida, dependendo das configurações de comutador, ele gera mensagens de depuração para entrar e sair do método.
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. Essas opções 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 uma opção. 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:DEBUGsinalizador à linha de comando do compilador ao compilar seu código ou adicione#define DEBUGà parte superior do arquivo. No Visual Basic, adicione o/d:DEBUG=Truesinalizador à linha de comando do compilador.Para habilitar o rastreamento usando em C#, adicione o
/d:TRACEsinalizador à linha de comando do compilador ao compilar seu código ou adicione#define TRACEà parte superior do arquivo. No Visual Basic, adicione o/d:TRACE=Truesinalizador à 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 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="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 = 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
| Nome | Description |
|---|---|
| Switch(String, String, String) |
Inicializa uma nova instância da Switch classe, especificando o nome de exibição, a descrição e o valor padrão para a opção. |
| Switch(String, String) |
Inicializa uma nova instância da classe Switch. |
Propriedades
| Nome | Description |
|---|---|
| Attributes |
Obtém os atributos de comutador personalizados definidos no arquivo de configuração do aplicativo. |
| DefaultValue |
Obtém o valor padrão atribuído no construtor. |
| Description |
Obtém uma descrição da opção. |
| DisplayName |
Obtém um nome usado para identificar a opção. |
| 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
| Nome | Description |
|---|---|
| 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 compatíveis com a opção. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| OnSwitchSettingChanged() |
Invocado quando a SwitchSetting propriedade é alterada. |
| OnValueChanged() |
Invocado quando a Value propriedade é alterada. |
| Refresh() |
Atualiza os dados de configuração de rastreamento. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual. (Herdado de Object) |
Eventos
| Nome | Description |
|---|---|
| Initializing |
Ocorre quando é Switch necessário inicializar. |