常规用法:

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)]();
}


最新文章

  1. 底部漂浮DIV
  2. HTML与HTML5笔记
  3. CSS笔记(五)字体
  4. C#序列化XML至对象
  5. 如何在网页中显示pdf
  6. Android PackageManager基础知识
  7. centos6.4-x86-64系统更新系统自带Apache Http Server
  8. 数据库CAST()函数和CONVERT()函数比较
  9. asp.net core源码飘香:Logging组件
  10. my97自定义事件
  11. Hibernate开发文档
  12. tf.contrib.slim arg_scope
  13. MySQL binlog_format中sbr 和rbr(Statement-Based and Row-Based Replication)的优缺点
  14. eclipse编译器显示的文件名乱码,活动标签乱码(已解决)
  15. Confluence 6 下载和安装 MySQL 驱动
  16. Android 四大组件 Service 服务
  17. commons-beanutils的使用
  18. Git学习(一)(2015年11月12日)
  19. HUE配置文件hue.ini 的zookeeper模块详解(图文详解)(分HA集群)
  20. :Linux 系统日志管理 日志转储

热门文章

  1. 转:C# 定时任务实现
  2. 通过基于 Linux 的软件 VPN 设备连接到 Windows Azure 虚拟网络
  3. Java日志终极指南
  4. 关于sem_unlink什么时候删除信号量
  5. Android学习总结——去除标题栏
  6. python实现二叉树和它的七种遍历
  7. hdu1171 Big Event in HDU 01-背包
  8. ACM-简单题之Ignatius and the Princess II——hdu1027
  9. MYSQL免安装版使用说明
  10. python -序列化