Switch Класс
Определение
Предоставляет абстрактный базовый класс для создания новых переключателей отладки и трассировки.Provides an abstract base class to create new debugging and tracing switches.
public ref class Switch abstract
public abstract class Switch
type Switch = class
Public MustInherit Class Switch
- Наследование
-
Switch
- Производный
Примеры
В следующем примере показано, как определить новый Switch класс с четырьмя уровнями трассировки, которые можно использовать для трассировки стека вызовов.The following example shows how to define a new Switch class with four levels of tracing that can be used to trace a call stack. Можно использовать параметр, чтобы инструментировать приложение для записи при каждом входе или выходе из метода.You can use the switch to instrument your application to log each time the method is entered or exited.
В первом примере создается перечисление, используемое для задания уровня переключателя.The first example creates the enumeration used to set the level of the switch.
// 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
В следующем примере создается новый параметр.The following example creates the new switch. В коде реализуется Level
свойство для задания значения нового переключателя.The code implements a Level
property to set the value of the new switch. Level
вызывает защищенное свойство SwitchSetting , которое присваивает значение новому переключателю.Level
calls the protected property SwitchSetting that assigns the value to the new switch. В этом примере также реализуются два свойства оценки для получения назначенного значения переключателя.This example also implements two assessor properties to get the assigned value of the switch.
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
В следующем примере создается новый переключатель в Main
.The following example creates a new switch in Main
. Он создает новый переключатель и присваивает ему значение.It creates a new switch and assigns it a value. Затем, в зависимости от параметров коммутатора, он выводит сообщения отладки для ввода и выхода из метода.Then, depending on the switch settings, it outputs debugging messages for entering and leaving the method.
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
Комментарии
Коммутатор предоставляет эффективный механизм управления выводом трассировки и отладки во время выполнения с использованием внешних параметров.A switch provides an efficient mechanism for controlling tracing and debugging output at run time using external settings. SwitchКласс реализует поведение по умолчанию для переключателей, что позволяет изменять уровень коммутатора во время выполнения.The Switch class implements default behavior for switches, allowing you to change the switch level at run time.
Этот класс является базовым классом для BooleanSwitch SourceSwitch классов, и TraceSwitch .This class is the base class for the BooleanSwitch, SourceSwitch and the TraceSwitch classes. Эти коммутаторы отвечают большинству задач отладки и трассировки.These switches meet most debugging and tracing needs. Дополнительные сведения о параметрах трассировки см. в разделе Параметры трассировки.For more information about trace switches, see Trace Switches.
Для использования переключателя необходимо включить трассировку или отладку.You must enable tracing or debugging to use a switch. Ниже приведен синтаксис, характерный для компилятора.The following syntax is compiler specific. Если используются компиляторы, отличные от C# или Visual Basic, обратитесь к документации по компилятору.If you use compilers other than C# or Visual Basic, refer to the documentation for your compiler.
Чтобы включить отладку в C#, добавьте
/d:DEBUG
флаг в командную строку компилятора при компиляции кода или добавьте#define DEBUG
в начало файла.To enable debugging in C#, add the/d:DEBUG
flag to the compiler command line when you compile your code, or you can add#define DEBUG
to the top of your file. В Visual Basic добавьте/d:DEBUG=True
флаг в командную строку компилятора.In Visual Basic, add the/d:DEBUG=True
flag to the compiler command line.Чтобы включить трассировку с помощью в C#, добавьте
/d:TRACE
флаг в командную строку компилятора при компиляции кода или добавьте#define TRACE
в начало файла.To enable tracing using in C#, add the/d:TRACE
flag to the compiler command line when you compile your code, or add#define TRACE
to the top of your file. В Visual Basic добавьте/d:TRACE=True
флаг в командную строку компилятора.In Visual Basic, add the/d:TRACE=True
flag to the compiler command line.
Чтобы задать уровень коммутатора, измените файл конфигурации, соответствующий имени приложения.To set the level of your switch, edit the configuration file that corresponds to the name of your application. В этом файле можно добавить переключатель и задать его значение, удалить переключатель или очистить все параметры, заданные приложением ранее.Within this file, you can add a switch and set its value, remove a switch, or clear all the switches previously set by the application. Файл конфигурации следует отформатировать, как показано в следующем примере:The configuration file should be formatted like the following example:
<configuration>
<system.diagnostics>
<switches>
<add name="mySwitch" value="true" />
</switches>
</system.diagnostics>
</configuration>
В этом примере раздела конфигурации определяется BooleanSwitch свойство со DisplayName свойством, для которого задано mySwitch
значение, а Enabled для значения — true
.This example configuration section defines a BooleanSwitch with the DisplayName property set to mySwitch
and the Enabled value set to true
. В приложении можно использовать настроенное значение переключателя, создав BooleanSwitch с тем же именем, как показано в следующем примере кода.Within your application, you can use the configured switch value by creating a BooleanSwitch with the same name, as shown in the following code example.
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)
{
//...
}
}
Примечания для тех, кто реализует этот метод
Если вам нужны уровни трассировки или механизмы для настройки уровней переключателей, отличающиеся от методов BooleanSwitch , предоставляемых, SourceSwitch и TraceSwitch , можно наследовать от Switch .If you need trace levels, or mechanisms for setting switch levels different from those provided by BooleanSwitch, SourceSwitch and TraceSwitch, you can inherit from Switch. При наследовании от этого класса необходимо реализовать SwitchSetting метод.When inheriting from this class, you must implement the SwitchSetting method.
Конструкторы
Switch(String, String) |
Инициализирует новый экземпляр класса Switch.Initializes a new instance of the Switch class. |
Switch(String, String, String) |
Инициализирует новый экземпляр класса Switch, указывая отображаемое имя, описание и значение по умолчанию переключателя.Initializes a new instance of the Switch class, specifying the display name, description, and default value for the switch. |
Свойства
Attributes |
Получает настраиваемые атрибуты переключателя, определенные в файле конфигурации приложения.Gets the custom switch attributes defined in the application configuration file. |
Description |
Получает описание переключателя.Gets a description of the switch. |
DisplayName |
Получает имя, идентифицирующее переключатель.Gets a name used to identify the switch. |
SwitchSetting |
Получает или задает текущее положение данного переключателя.Gets or sets the current setting for this switch. |
Value |
Получает или задает значение переключателя.Gets or sets the value of the switch. |
Методы
Equals(Object) |
Определяет, равен ли указанный объект текущему объекту.Determines whether the specified object is equal to the current object. (Унаследовано от Object) |
GetHashCode() |
Служит хэш-функцией по умолчанию.Serves as the default hash function. (Унаследовано от Object) |
GetSupportedAttributes() |
Возвращает настраиваемые атрибуты, поддерживаемые переключателем.Gets the custom attributes supported by the switch. |
GetType() |
Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance. (Унаследовано от Object) |
MemberwiseClone() |
Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object. (Унаследовано от Object) |
OnSwitchSettingChanged() |
Вызывается при изменении свойства SwitchSetting.Invoked when the SwitchSetting property is changed. |
OnValueChanged() |
Вызывается при изменении свойства Value.Invoked when the Value property is changed. |
ToString() |
Возвращает строку, представляющую текущий объект.Returns a string that represents the current object. (Унаследовано от Object) |