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

标签 c# generics c#-8.0 non-nullable nullable-reference-types

这篇文章是针对 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;

关于c# - 如何将 "any non-nullable type"指定为泛型类型参数约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57335449/

相关文章:

c# - 自定义控件不显示

c# - DataGridView 的替代品

java - 为什么我不能直接转换 super 调用的结果?

Kotlin 泛型 : Cannot sort by type with star projected parameter

c# - 确定类型引用是否可为空/不可空

c# - 如何使用 Entity Framework 保存外键?

c# - 如何强制触发 OnModelCreating 每个 DataContext 初始化

java - 具有抽象泛型的抽象类?

c# - 如何在子接口(interface)中提供默认实现?