c# - C#泛型类:从可空类型参数推断不可空类型
问题描述
我使用 C# 8 可空引用类型。
我有一个泛型类,它可能接受可为空的引用类型作为类型参数。
有没有办法根据可能是可为空引用类型(甚至可为 Nullable 结构)的泛型类型参数声明不可为空的类型?
abstract class Selector<T>
{
T SelectedItem;
// how to make item parameter not nullable?
abstract string Format(T! item);
// how to make item parameter not nullable?
Func<T!, string> FormatFunction;
}
解决方案
using System.Diagnostics.CodeAnalysis;
abstract class Selector<T>
{
T SelectedItem;
public abstract string Format([DisallowNull] T item);
}
var selector = default(Selector<string?>)!;
selector.Format(null); //warning CS8625: Cannot convert null literal to non-nullable reference type.
推荐阅读
- xcode - CocoaPods 要求您的终端使用 UTF-8 编码。考虑将以下内容添加到 ~/.profile:export LANG=en_US.UTF-8
- jquery - 根据活动父元素JQuery将tabindex设置为子元素
- javascript - 是否保证在 `touchend` 之后、`touchend` 的事件处理程序可以运行之前触发`click` 事件?
- javascript - Jasmine 测试 - 附加元素的持久性以及点击触发多次的原因
- angular - 如何使用 OnPush 更改检测显示加载模板?
- vue.js - 可以从 19 小时前粘贴 Package-Lock.json 以修复“ValidationError:Progress Plugin Invalid Options”(Vue 3)吗?
- c++ - 为什么这个最小的 SDL/OpenGL 示例在与 GL 而不是 OpenGL 链接时有效?
- php - OpenLiteSpeed 上的 MSSQL PDO?
- netcdf - 使用 ncra --mro 从月产量计算年均值
- django - Django Template js静态文件无法加载