[英]the type (my class) must be non-nullable type in order to use as a parameter 'T' in a generic method
[英]C# Generic class: infer non-nullable type from nullable type parameter
我使用 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.