在使用可为空的引用类型和泛型类型时得到警告

时间:2019-12-08 17:04:24

标签: c# c#-8.0

我有一个类似的通用类型,它带有一个名为ExecuteAsync的方法,该方法可以返回一个对象或null:

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

public class StoreProcedure<Result, Schema> : IStoreProcedure<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 IStoreProcedure<Content?, API_Content_Get> _api_Content_Get;
    public ContentService(IStoreProcedure<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,我得到以下警告:

enter image description here

我找不到显示内容可以为空的方法。我可以这样写,并且不会收到警告,但假定结果值不为null;

private readonly IStoreProcedure<Content, API_Content_Get> _api_Content_Get;
    public ContentService(IStoreProcedure<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;
    }

我知道这只是一个警告,并不影响该过程。但是我有什么可以解决的吗?

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

1 个答案:

答案 0 :(得分:0)

看起来是您要使用的语法:

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

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