6.3. Creating Your Own Custom Switch Class
Problem
The BooleanSwitch
and
TraceSwitch
classes defined in the FCL may not
always have the required flexibility or fine-grained control that you
need. You want to create you own switch class that provides the level
of control and flexibility that you need. For example, creating a
class that allows you to set more precise trace levels than those
supported by the TraceSwitch
class.
The
TraceSwitch
class provides the following tracing
levels:
TraceError
|
TraceWarning
|
TraceInfo
|
TraceVerbose
|
However, you need a finer-grained set of levels, such as the following:
|
| ||
|
| ||
|
|
Solution
You can create your own switch class that inherits from
System.Diagnostics.Switch
and provides the level
of control that you need. For example, creating a class that allows
you to set more precise trace levels than those supported by the
TraceSwitch
class involves the following steps:
Define a set of enumerated values that represent the levels to be supported by your switch class:
public enum AppSpecificSwitchLevel { Disable = 0, Note = 1, Warning = 2, MinorError = 3, MediumError = 4, CriticalError = 5 }
Define a class, such as
AppSpecificSwitch
, that inherits fromSystem.Diagnostics.Switch
:public class AppSpecificSwitch : Switch { protected AppSpecificSwitchLevel level = 0; public AppSpecificSwitch(string displayName, string description) : base(displayName, description) { this.Level = (AppSpecificSwitchLevel)base.SwitchSetting; ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.