c# - 可空泛型引用类型

标签 c# c#-8.0 nullable-reference-types

我使用 C#8 实现了以下(工作)服务,但禁用了可空引用类型:

public class Foo { }

public interface IFooService
{
    Task<T> Get<T>() where T : Foo;
}

public FooService : IFooService
{
    async Task<T> IFooService.Get<T>() { /* returns either a valid Foo implementation or null */ }
}

我尝试启用 C#8 可空引用类型,但无论我做什么,似乎都无法摆脱错误或警告。新的接口(interface)类型是:

public interface IFooService
{
    // T IS nullable AND a reference type.
    // There is no ambiguity as of 'T?' meaning here, because it can't be a struct.
    Task<T?> Get<T>() where T : Foo;
}

当我使用以下实现时:

public class FooService : IFooService
{
    async Task<T?> IFooService.Get<T>() { /* ... */ }
}

我收到错误:

'FooService' does not implement interface member 'IFooService.Get<T>()'

我不明白,因为接口(interface)和实现中的签名完全相同。

但是,当我按如下方式实现接口(interface)时(这是 Visual Studio 自动实现生成的签名):

public class FooService : IFooService
{
    async Task<T> IFooService.Get<T>() { /* ... */ }
}

我收到以下警告:

Nullability of reference types in return type doesn't match implemented member 'Task<T?> IFooService.Get<T>()'.

最佳答案

您需要将通用约束添加到您的实现中:

public class FooService : IFooService
{
    async Task<T?> IFooService.Get<T>() where T : class
    {
        /* ... */ 
    }
}

有趣的是,Visual Studio 不会将 T? 添加到它生成的实现中。我怀疑这是编辑器中的错误。

您提到您的类型约束实际上是针对 Foo 的。这意味着您的代码将如下所示:

public class Foo
{
}

public interface IFooService
{
    // T IS nullable AND a reference type.
    // There is no ambiguity as of 'T?' meaning here, because it can't be a struct.
    Task<T?> Get<T>() where T : Foo;
}

public class FooService : IFooService
{
    async Task<T?> IFooService.Get<T>() where T : class
    {
        throw new NotImplementedException();
    }
}

类型约束位于接口(interface)上,但在实现上您无法指定实际的类型名称,但您可以指示它必须是一个类。

关于c# - 可空泛型引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61015912/

相关文章:

c# - 如何使用 C# 将 Windows 系统时钟设置为正确的本地时间?

c# - 在 C# 8.0 中,有没有办法公开类的默认成员实现?

c# - 不可为空的引用类型 : why is my object considered nullable by the compiler?

c# - 模式匹配和未分配的局部变量

c# - 可空引用类型 : How to specify "T?" type without constraining to class or struct

c# - 如果方法完全返回,请指定 NotNull

c# - 可为空的引用类型和构造函数警告

c# - ConcurrentDictionary + Lazy——实例化只会发生一次吗?

c# - 从哪里开始学习 LINQ 最好?

c# - 是否有使用 C#'s SortedDictionary<Key, Value> when you don' t 关心值的常用样式?