The value and switchsettings attributes of the system. Diagnostics. Switch class are protected modifiers and can be set. Value is a string type, and switchsetting is an int type. The value of the switch class is the value attribute. After the value is set, the switch attempts to convert the value string to the number of switchsetting. If the conversion fails, an exception is thrown.
When customizing the switch class, you can rewrite the onvaluechanged and onswitchsettingchanged methods to customize the actions after the Value Attribute and switchsetting attribute are changed.
We can customize a simple switch type: myswitch. After the value is set, convert the value to a number and assign it to the switchsetting attribute. If the value cannot be converted, no exception is thrown. The switchsetting attribute remains at the default value: 0.
// + Using system. Diagnostics
Class Myswitch:Switch
{
PublicMyswitch (StringName,StringDescription= Null)
:Base(Name, description)
{}
// Change the original protected attribute of the switch to public.
Public New StringValue
{
Get
{
Return Base.Value;
}
}
Public New IntSwitchsetting
{
Get
{
Return Base.Switchsetting;
}
}
// Manually rewrite the switch. onvaluechanged method to update the switchsetting attribute when the value attribute changes.
Protected Override VoidOnvaluechanged ()
{
IntI;
If(Int32.Tryparse (value,OutI ))
Base.Switchsetting=I;
}
Public Override StringTostring ()
{
Return String.Format ("Value: {0}, switchsetting: {1 }", Value, switchsetting );
}
}
In. netProgramIn the configuration file (App. config), <system. you can set a predefined switch for the <switches> element in the diagnostics> element. To add a switch, you need to set the switch name and value (using the XML Attribute: Name and value ).
For example, five switches are defined as follows:
<Configuration>
<System. Diagnostics>
<Switches>
<Add Name="S1" Value="False"/>
Add name = " S2 " value = " 19 " />
Add name = " S3 " value = " mgen " />
Add name = " S4 " value = " -2 " />
<Add Name="S5" Value="Error"/>
</Switches>
</System. Diagnostics>
</Configuration>
Then, you can use multiple switches in. Net: booleanswitch, traceswitch, sourceswitch, and our custom type: myswitch to read these switches.
// + Using system. Diagnostics
// The above custom class is required: myswitch
VaRBoolswitch= New Booleanswitch("S1",Null);
Console.Writeline (boolswitch.Enabled );
Boolswitch= New Booleanswitch("S2",Null);
Console.Writeline (boolswitch.Enabled );
VaRMyswitch= New Myswitch("S3");
Console.Writeline (myswitch );
Myswitch= New Myswitch("S4");
Console.Writeline (myswitch );
VaRTraceswitch= New Traceswitch("S5",Null);
Console.Writeline (traceswitch.Level );
VaRSourceswitch= New Sourceswitch("S5",Null);
Console.Writeline (sourceswitch.Level );
Output:
False
True
Value: mgen, switchsetting: 0
Value:-2, switchsetting:-2
Error
Error