gpt4 book ai didi

c# - 为什么 Dictionary 不支持空键?

转载 作者:IT王子 更新时间:2023-10-29 03:54:47 25 4
gpt4 key购买 nike

<分区>

首先,为什么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());
}
}

用于打开类型。有两种使用方式:

  1. 静态的。只需调用 Switch.Execute(yourObject, Switch.Case<YourType>(x => x.Action()))
  2. 预编译。创建一个开关,稍后将其与 switchInstance.Execute(yourObject) 一起使用

当您尝试向“预编译”版本(空参数异常)添加默认情况时,效果很好

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com