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