我的代码看起来像这样:
#nullable enable
class MyClass<KEY, ITEM>
{
readonly Dictionary<KEY, ITEM> Map = new Dictionary<KEY, ITEM>();
public void Process(KEY key, ITEM item)
{
if (key != null)
{
Map[key] = item;
}
}
}
#nullable disable
编译器对此并不感兴趣,它给了我警告
type 'KEY' cannot be used as type parameter 'TKey' in the generic type or method 'Dictionary<TKey, TValue>
我当然可以理解。问题是,向 Process() 发送 'key' 参数的 null 是完全有效的,因此我无法将“where KEY: notnull”约束添加到类中。(并且 MyClass 需要接受 KEY 类型参数的类和结构)
我唯一能想到的是:
#nullable enable
class MyClass<KEY, ITEM>
{
#nullable disable
readonly Dictionary<KEY, ITEM> Map = new Dictionary<KEY, ITEM>();
#nullable enable
public void Process(KEY key, ITEM item)
{
if (key != null)
{
Map[key] = item;
}
}
}
#nullable disable
这让编译器很高兴,但是我没有那些漂亮的 C# 8 空检查。例如,它允许我编写以下代码:
Map[default] = item;
并且编译器不会眨眼。
如何告诉编译器 Dictionary<> 的 'KEY' 类型参数应该不允许空值,但仍允许外部类中的 KEY 值为空?
编辑
我想使用新的 C# 8 可空性功能,以便在编译时捕获尽可能多的空指针(而不是等待运行时异常)。
进一步编辑
我现在的方向是在 Dictionary 周围放置一个薄层以强制执行 null 限制并使用它而不是 Dictionary<>
#nullable enable
public class CheckDictionary<KEYTYPE, VALUETYPE>
{
#nullable disable
readonly Dictionary<KEYTYPE, VALUETYPE> Dictionary = new Dictionary<KEYTYPE, VALUETYPE>();
#nullable enable
public VALUETYPE this[[DisallowNull] KEYTYPE key]
{
get { return Dictionary[key]; }
set { Dictionary[key] = value; }
}
public bool Remove([DisallowNull] KEYTYPE key)
{ return Dictionary.Remove(key); }
public bool TryGetValue([DisallowNull] KEYTYPE key, out VALUETYPE value)
{ return Dictionary.TryGetValue(key, out value); }
public List<VALUETYPE> Values => Dictionary.Values.ToList();
}