• 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)]();
    }
  • 相关阅读:
    套用JQuery EasyUI列表显示数据、分页、查询
    Linux 进程间通信 信号
    Linux socket编程
    Linux字符设备驱动注册流程
    Linux杂项设备与字符设备
    Linux并发控制解决竞态的一种操作>原子操作
    Linux 进程间通信 管道通信
    Linux串口编程
    博客开通啦!
    实现Windows Phone 8多媒体:视频
  • 原文地址:https://www.cnblogs.com/jinacookies/p/3178282.html
Copyright © 2020-2023  润新知