首页 > 解决方案 > 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;
}

标签: c#genericsnullable-reference-typesnon-nullablec#-9.0

解决方案


使用DisallowNullAttribute

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.

推荐阅读