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)]();
    }
  • 相关阅读:
    面试题目整理(MySQL系列-调优)
    面试题目整理(MySQL系列-事务)
    面试题目整理(MySQL系列-索引)
    MySQL遇到问题
    Gorm的高级用法
    Gorm的初步使用(使用频率排序)
    MySQL索引详解
    SSH命令行上传/下载文件
    SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_unicode_ci,COERCIBLE) for operation 'like' 。。。
    Redis 缓存穿透、缓存雪崩、缓存击穿解决方案
  • 原文地址:https://www.cnblogs.com/jinacookies/p/3178282.html
Copyright © 2011-2022 走看看