这里也有个新鲜的用法
通常判断一个控件类型时,我们用样:
void Do(Control c)
{
Label l;
Button b;
if ((l as Label) != null)
{
// ...
}
else if ((c as Button) != null)
{
// ...
}
else
{
// ...
}
}
使用扩展的Switch可以这样.
void Do(Control c)
{
new Switch(c)
.Case<Label>(l =>
{
// ...
})
.Case<Button>(b =>
{
// ...
})
.Default(cc =>
{
// ...
});
}
普通的switch用这个替换
void Do(string name)
{
new Switch<string>(name)
.Case(s => s.StartsWith("B"), s =>
{
Console.WriteLine(s + " starts with B.");
}, true)
.Case(s => s.StartsWith("Ba"), s =>
{
Console.WriteLine(s + " starts with Ba.");
})
.Default(s =>
{
Console.WriteLine(s + " starts with who knows what.");
});
}
详细看原文。
http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx