【发布时间】:2021-02-17 21:48:03
【问题描述】:
我使用 C# 8 可空引用类型。
我有一个泛型类,它可能接受可为空的引用类型作为类型参数。
有没有办法根据泛型类型参数声明不可为空的类型,该类型参数可能是可空引用类型(甚至是可空结构)?
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;
}
【问题讨论】:
-
您应该考虑使用属性而不是
!和?符号来表示可空性。由于可空值类型和引用类型的实现完全不同,因此没有简单的通用方法来处理两者。
标签: c# generics nullable-reference-types non-nullable c#-9.0