【问题标题】:C# Generic class: infer non-nullable type from nullable type parameterC#泛型类:从可空类型参数推断不可空类型
【发布时间】: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


【解决方案1】:

使用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.

【讨论】:

  • 哦,我刚刚意识到我也需要它来用于像 Action 这样的委托或自定义委托。至少对于引用类型是可能的吗?
  • 这似乎是一个不错的选择,但此属性不适用于 .Net Framework。在 .Net Framework 中使用它们是否有任何提示?
  • 您可以自己定义它们 - 只要确保它们是内部的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多