如何将 "any non-nullable type" 指定为泛型类型参数约束?

How do I specify "any non-nullable type" as a generic type parameter constraint?

post 特定于 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>
  …
</Project>

此代码将产生以下构建时错误:

DictionaryEx.cs(28, 78): [CS8714] The type 'TKey' cannot be used as type parameter 'TKey' in the generic type or method 'Dictionary'. Nullability of type argument 'TKey' doesn't match 'notnull' constraint.

有什么方法可以指定 TKey 必须是不可为 null 的类型吗?

好的,刚刚发现您可以使用 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;