View Code

C# Switch is Type

常规用法:

Type t = sender.GetType();
if (t == typeof(Button)) {
    var realObj = (Button)sender;
    // Do Something
}
else if (t == typeof(CheckBox)) {
    var realObj = (CheckBox)sender;
    // Do something else
}
else {
    // Default action
}

非常规方法一:

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"));
 
相应的静态类
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 || type == entry.Target) {
                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
        };
    }
}

方法二:

定义:var @switch = new Dictionary<Type, Action> {
    { typeof(Type1), () => ... },
    { typeof(Type2), () => ... },
    { typeof(Type3), () => ... },
};
@switch[typeof(MyType)]();

使用:

if(@switch.ContainsKey(typeof(MyType))) {
@switch[typeof(MyType)]();
}
posted on 2013-07-08 16:38  湘军投研  阅读(2777)  评论(1编辑  收藏  举报