在C#中,类型开关明显不足(更新:在C#7 / VS 2017中支持类型开关 - 请参见Zachary Yates的答案)。为了避免使用大量的if / else if / else语句,您需要使用不同的结构。我之前写过一篇博客文章,详细介绍如何构建TypeSwitch结构。
https://learn.microsoft.com/archive/blogs/jaredpar/switching-on-types
简短版本:TypeSwitch旨在防止冗余转换,并提供类似于普通switch / case语句的语法。例如,以下是在标准Windows窗体事件上运行TypeSwitch的示例:
TypeSwitch.Do(
sender,
TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));
TypeSwitch的代码实际上非常小,可以轻松地放入您的项目中。
static class TypeSwitch {
public class CaseInfo {
public bool IsDefault { get; set; }
public Type Target { get; set; }
public Action<object> Action { get; set; }
}
public static void Do(object source, params CaseInfo[] cases) {
var type = source.GetType();
foreach (var entry in cases) {
if (entry.IsDefault || entry.Target.IsAssignableFrom(type)) {
entry.Action(source);
break;
}
}
}
public static CaseInfo Case<T>(Action action) {
return new CaseInfo() {
Action = x => action(),
Target = typeof(T)
};
}
public static CaseInfo Case<T>(Action<T> action) {
return new CaseInfo() {
Action = (x) => action((T)x),
Target = typeof(T)
};
}
public static CaseInfo Default(Action action) {
return new CaseInfo() {
Action = x => action(),
IsDefault = true
};
}
}