System.Diagnostics.Switch類的Value和SwitchSettings屬性是protected修飾符,並且是可以設定的。Value是字串類型,SwitchSetting是int類型。Switch類的值是Value屬性,當值被設定後,Switch會嘗試將Value字串轉換成SwitchSetting的數字。如果無法成功轉換,異常將會被拋出。
當自訂Switch類時,可以改寫OnValueChanged和OnSwitchSettingChanged方法來自訂Value屬性和SwitchSetting屬性改變後的動作。
我們自訂一個簡單的Switch類型:MySwitch。當Value被設定後,嘗試將Value轉換成數字並賦值給SwitchSetting屬性,如果無法轉換則不會拋出異常,SwitchSetting屬性保持預設值:0。
//+ using System.Diagnostics
class MySwitch : Switch
{
public MySwitch(string name, string description = null)
: base(name, description)
{ }
//把Switch原有的protected屬性改成public
public new string Value
{
get
{
return base.Value;
}
}
public new int SwitchSetting
{
get
{
return base.SwitchSetting;
}
}
//手動改寫Switch.OnValueChanged方法,來當Value屬性改變後更新SwitchSetting屬性
protected override void OnValueChanged()
{
int i;
if (Int32.TryParse(Value, out i))
base.SwitchSetting = i;
}
public override string ToString()
{
return String.Format("Value: {0}, SwitchSetting: {1}", Value, SwitchSetting);
}
}
在.NET程式的設定檔中(app.config),<system.diagnostics>元素中的<switches>元素可以設定一個預定義的開關,添加開關需要設定開關的名稱和值(通過XML屬性:name和value)。
比如定義這樣5個開關:
<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>
然後可以用.NET中的多種開關:BooleanSwitch, TraceSwitch, SourceSwitch和我們自訂的類型:MySwitch來讀取這些開關。
//+ using System.Diagnostics
//需要上面的自訂類:MySwitch
var boolSwitch = new BooleanSwitch("s1", null);
Console.WriteLine(boolSwitch.Enabled);
boolSwitch = new BooleanSwitch("s2", null);
Console.WriteLine(boolSwitch.Enabled);
var mySwitch = new MySwitch("s3");
Console.WriteLine(mySwitch);
mySwitch = new MySwitch("s4");
Console.WriteLine(mySwitch);
var traceSwitch = new TraceSwitch("s5", null);
Console.WriteLine(traceSwitch.Level);
var sourceSwitch = new SourceSwitch("s5", null);
Console.WriteLine(sourceSwitch.Level);
輸出:
False
True
Value: Mgen, SwitchSetting: 0
Value: -2, SwitchSetting: -2
Error
Error