【发布时间】:2011-06-05 16:47:07
【问题描述】:
首先,为什么Dictionary<TKey, TValue>不支持单个空键?
其次,是否存在类似字典的集合?
我想存储一个“空”或“缺失”或“默认”System.Type,我认为null 可以很好地解决这个问题。
更具体地说,我编写了这个类:
class Switch
{
private Dictionary<Type, Action<object>> _dict;
public Switch(params KeyValuePair<Type, Action<object>>[] cases)
{
_dict = new Dictionary<Type, Action<object>>(cases.Length);
foreach (var entry in cases)
_dict.Add(entry.Key, entry.Value);
}
public void Execute(object obj)
{
var type = obj.GetType();
if (_dict.ContainsKey(type))
_dict[type](obj);
}
public static void Execute(object obj, params KeyValuePair<Type, Action<object>>[] cases)
{
var type = obj.GetType();
foreach (var entry in cases)
{
if (entry.Key == null || type.IsAssignableFrom(entry.Key))
{
entry.Value(obj);
break;
}
}
}
public static KeyValuePair<Type, Action<object>> Case<T>(Action action)
{
return new KeyValuePair<Type, Action<object>>(typeof(T), x => action());
}
public static KeyValuePair<Type, Action<object>> Case<T>(Action<T> action)
{
return new KeyValuePair<Type, Action<object>>(typeof(T), x => action((T)x));
}
public static KeyValuePair<Type, Action<object>> Default(Action action)
{
return new KeyValuePair<Type, Action<object>>(null, x => action());
}
}
用于打开类型。有两种使用方式:
- 静态。只需致电
Switch.Execute(yourObject, Switch.Case<YourType>(x => x.Action())) - 预编译。创建一个开关,稍后将其与
switchInstance.Execute(yourObject)一起使用
当您尝试将默认情况添加到“预编译”版本(空参数异常)时,效果很好except。
【问题讨论】:
标签: c#