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)]();
    }
  • 相关阅读:
    Unity3D 中的灯光与渲染
    利用正态分布(高斯分布)绘制噪点图
    Unity3D 调用相机
    Unity3D开发安卓应用如何设置横屏显示和竖屏显示
    Unity3D中Excel表的读取与写入
    Unity3D启动外部程序并传递参数
    Unity动画系统Animator动态添加事件
    Unity3D编辑器扩展(六)——模态窗口
    Unity3D编辑器扩展(五)——常用特性(Attribute)以及Selection类
    Unity3D编辑器扩展(四)——扩展自己的组件
  • 原文地址:https://www.cnblogs.com/jinacookies/p/3178282.html
Copyright © 2011-2022 走看看