该帖子专门针对C#8。让我们假设我要使用此方法:
public static TValue Get<TKey, TValue>(
this Dictionary<TKey, TValue> src,
TKey key, TValue @default)
=> src.TryGetValue(key, out var value) ? value : @default;
如果我的.csproj如下所示(即启用了C#8和可为空的类型,则所有警告均为错误):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<LangVersion>8</LangVersion>
<Nullable>enable</Nullable>
<WarningsAsErrors>true</WarningsAsErrors>
</PropertyGroup>
...
此代码将产生以下构建时错误:
DictionaryEx.cs(28, 78): [CS8714] The type 'TKey' cannot
be used as type parameter 'TKey' in the generic type or
method 'Dictionary<TKey, TValue>'. Nullability of type argument
'TKey' doesn't match 'notnull' constraint.
是否有任何方法可以指定TKey
必须是非空类型?
答案 0 :(得分:7)
好吧,刚发现您可以使用notnull约束:
public static TValue Get<TKey, TValue>(
this Dictionary<TKey, TValue> src,
TKey key, TValue @default)
where TKey : notnull
=> src.TryGetValue(key, out var value) ? value : @default;