使用.NET 5 SDK编译IDictionary扩展方法时触发CS8620可空性差异报错
自定义IDictionary扩展方法的可空性编译报错问题
扩展方法实现代码
为实现从字典安全取值的能力,为IDictionary<TKey, T>编写了带默认返回值的扩展方法,其中无自定义默认值的重载会传入default(T)调用带自定义默认值的重载,代码如下:
[return: MaybeNull] public static T GetValueOrDefault<TKey, T>(this IDictionary<TKey, T> source, TKey key) where TKey : notnull { return GetValueOrDefault(source, key, defaultValue: default); } [return: MaybeNull] public static T GetValueOrDefault<TKey, T>(this IDictionary<TKey, T> source, TKey key, [AllowNull] T defaultValue) where TKey : notnull { if (source is null) throw new ArgumentNullException(nameof(source)); if (key is null) throw new ArgumentNullException(nameof(key)); if (source.TryGetValue(key, out var item)) { return item; } return defaultValue; }
跨版本编译差异表现
- 在.NET SDK 3.1.100环境下,上述代码可正常编译通过
- 在.NET SDK 5.0.101环境下,会触发可空性相关的编译错误:
错误 CS8620:由于引用类型的可空性存在差异,类型为
IDictionary<TKey, T>的实参无法用于T? DictionaryExtensions.GetValueOrDefault<TKey, T?>(IDictionary<TKey, T?> source, TKey key, T? defaultValue)中类型为IDictionary<TKey, T?>的source形参。
报错指向无自定义默认值重载中,调用带参重载时传入default作为默认值的代码行。
排查过程中观察到的现象
- 临时改用
default!可消除该编译错误,但这种处理不符合设计预期:defaultValue参数本身就是允许传入null值的,这也是在参数上标注[AllowNull]特性的原因,不希望通过无意义的null宽容性操作符压制告警 - 对报错原因的初步推测:是不是编译器因为
[AllowNull]标注的存在,将泛型参数T推断为可空版本T?,导致实际传入的可空性不匹配的IDictionary<TKey, T>,不符合形参要求的IDictionary<TKey, T?>类型? - 报错存在明确的触发边界:只有当泛型参数
T未被约束为class类型时才会出现报错,以下场景的调用不会触发任何可空性相关的告警:
var dict = new Dictionary<string, string>(); dict.GetValueOrDefault("key", null);
核心疑问
- 上述扩展方法的实现存在哪些逻辑或可空性标注层面的问题
- .NET 5版本的SDK是否进一步收紧了可空引用类型的校验规则
- 这个特定场景下的编译报错,是否属于.NET SDK 5.0.101本身的实现缺陷
内容的提问来源于stack exchange,提问作者Thorkil Holm-Jacobsen
相关产品推荐
相关产品推荐

