使用具有泛型类型的可空引用类型时收到警告

Getting warning while using nullable reference type with a generic type

我有一个像下面这样的泛型类型,它有一个名为 ExecuteAsync() 的方法,它可以 return 一个对象或 null:


public interface IStoredProcedure<Result, Schema>
    where Result : IBaseEntity
    where Schema : IBaseSchema
{
    Task<Result> ExecuteAsync(Schema model);
}

public class StoredProcedure<Result, Schema> : IStoredProcedure<Result, Schema>
    where Result : IBaseEntity
    where Schema : IBaseSchema
{
    public async Task<Result> ExecuteAsync(Schema model){
        //I use QueryFirstOrDefaultAsync of Dapper here, which returns an object or null
        throw new NotImplementedException();
    }
}

我在我的服务中使用它如下:

public interface IContentService
{
    Task<Content?> Get(API_Content_Get schema);
}

public class ContentService : IContentService
{
    private readonly IStoredProcedure<Content?, API_Content_Get> _api_Content_Get;

    public ContentService(IStoredProcedure<Content?, API_Content_Get> api_Content_Get)
    {
        _api_Content_Get = api_Content_Get;
    }

    public async Task<Content?> Get(API_Content_Get schema)
    {
        Content? result = await _api_Content_Get.ExecuteAsync(schema);
        return result;
    }
}

如果我不在 ContentService 中添加 ? 以表明内容可以是 null,我会收到此警告:

我找不到显示内容可以 null 的方法。我可以按如下方式编写它,它不会收到任何警告,但它会假设结果值不是 null:

private readonly IStoredProcedure<Content, API_Content_Get> _api_Content_Get;
public ContentService(IStoredProcedure<Content, API_Content_Get> api_Content_Get)
{
    _api_Content_Get = api_Content_Get;
}

public async Task<Content?> Get(API_Content_Get schema)
{
    Content? result = await _api_Content_Get.ExecuteAsync(schema);
    return result;
}

我知道这只是一个警告,不影响进程。但是我能做些什么来修复它吗?

我认为这是应该修复的新功能中的错误。

看起来这就是您要的语法:

public interface IStoreProcedure<Result, Schema>
where Result : IBaseEntity?
where Schema : IBaseSchema {
   Task<Result> ExecuteAsync(Schema model);
}

似乎默认情况下,在可为空的上下文中,类型约束意味着不可为空,因此要获得可空性,您必须将 ? 添加到类型约束中。