zoukankan      html  css  js  c++  java
  • 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)]();
    }
  • 相关阅读:
    IntelliJ IDEA 16创建Web项目
    Error running Tomcat8: Address localhost:1099 is already in use 错误解决
    Hibernate的三种状态
    Hibernate 脏检查和刷新缓存机制
    Windows服务器时间不同步问题
    解决Windows内存问题的两个小工具RamMap和VMMap
    实现多线程异步自动上传本地文件到 Amazon S3
    JS判断用户连续输入
    ASP.Net 重写IHttpModule 来拦截 HttpApplication 实现HTML资源压缩和空白过滤
    bootstrap的popover在trigger设置为hover时不隐藏popover
  • 原文地址:https://www.cnblogs.com/jinacookies/p/3178282.html
Copyright © 2011-2022 走看看