Switch Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Fornece uma classe base abstrata para criar novos comutadores de depuração e rastreio.
public ref class Switch abstract
public abstract class Switch
type Switch = class
Public MustInherit Class Switch
- Herança
-
Switch
- Derivado
Exemplos
O exemplo seguinte mostra como definir uma nova Switch classe com quatro níveis de rastreio que podem ser usados para rastrear uma pilha de chamadas. Pode usar o interruptor para instrumentar a sua aplicação e registar cada vez que o método é introduzido ou encerrado.
O primeiro exemplo cria a enumeração usada para definir o nível do interruptor.
// 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 seguinte cria o novo interruptor. O código implementa uma Level propriedade para definir o valor do novo switch.
Level chama a propriedade SwitchSetting protegida que atribui o valor ao novo switch. Este exemplo também implementa duas propriedades do avaliador para obter o valor atribuído ao comutador.
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 seguinte cria um novo interruptor em Main. Cria um novo interruptor e atribui-lhe um valor. Depois, dependendo das definições do interruptor, 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
Observações
Um switch fornece um mecanismo eficiente para controlar a saída de rastreio e depuração em tempo de execução, utilizando definições externas. A Switch classe implementa o comportamento padrão dos switches, permitindo alterar o nível do switch em tempo de execução.
Esta classe é a classe base para as BooleanSwitchclasses, SourceSwitch, e TraceSwitch . Estes switches satisfazem a maioria das necessidades de depuração e rastreamento. Para mais informações sobre comutadores de trilho, consulte Comutadores de trilha.
Tens de ativar o rastreamento ou depuração para usar um switch. A sintaxe seguinte é específica do compilador. Se usar compiladores que não sejam C# ou Visual Basic, consulte a documentação do seu compilador.
Para permitir a depuração em C#, adicione a
/d:DEBUGflag à linha de comandos do compilador quando compilar o seu código, ou pode adicionar#define DEBUGno topo do seu ficheiro. Em Visual Basic, adicione a flag/d:DEBUG=Trueà linha de comandos do compilador.Para permitir o rastreamento usando em C#, adicione a
/d:TRACEflag à linha de comandos do compilador quando compilar o seu código, ou adicione#define TRACEno topo do seu ficheiro. Em Visual Basic, adicione a flag/d:TRACE=Trueà linha de comandos do compilador.
Para definir o nível do seu switch numa aplicação .NET Framework, edite o ficheiro de configuração que corresponde ao nome da sua aplicação. Dentro deste ficheiro, pode adicionar um interruptor e definir o seu valor, remover um interruptor ou limpar todos os interruptores previamente definidos pela aplicação. O ficheiro de configuração deve ser formatado como o seguinte exemplo:
<configuration>
<system.diagnostics>
<switches>
<add name="mySwitch" value="true" />
</switches>
</system.diagnostics>
</configuration>
Esta secção de configuração de exemplo define a com a DisplayName propriedade definida como mySwitch e o Enabled valor definido como true.BooleanSwitch Dentro da sua aplicação, pode usar o valor do switch configurado criando um BooleanSwitch com o mesmo nome, como mostrado no seguinte exemplo de código.
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 para Implementadores
Se precisar de níveis de traço, ou de mecanismos para definir níveis de interruptor diferentes dos fornecidos por BooleanSwitch, SourceSwitch e TraceSwitch, pode herdar de Switch. Ao herdar desta classe, deve implementar o SwitchSetting método.
Construtores
| Name | Description |
|---|---|
| Switch(String, String, String) |
Inicializa uma nova instância da Switch classe, especificando o nome de visualização, descrição e valor padrão do switch. |
| Switch(String, String) |
Inicializa uma nova instância da Switch classe. |
Propriedades
| Name | Description |
|---|---|
| Attributes |
Obtém os atributos personalizados do switch definidos no ficheiro de configuração da aplicação. |
| Description |
Recebe uma descrição da mudança. |
| DisplayName |
Recebe um nome usado para identificar o interruptor. |
| SwitchSetting |
Obtém ou define a configuração atual deste interruptor. |
| Value |
Obtém ou define o valor do interruptor. |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetSupportedAttributes() |
Obtém os atributos personalizados suportados pelo switch. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| OnSwitchSettingChanged() |
Invocado quando a SwitchSetting propriedade é alterada. |
| OnValueChanged() |
Invocado quando a Value propriedade é alterada. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |