首先,为什么不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); …Run Code Online (Sandbox Code Playgroud) c# ×1