如何解决C#泛型类:从可为空的类型参数中推断不可为空的类型
我使用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;
}
解决方法
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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。