使用可空引用类型和泛型类型时出现警告

3

我有一个通用类型,像以下这样,拥有一个名为ExecuteAsync()的方法,可以返回一个对象或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,我会得到以下警告: enter image description here 我找不到一种方法来显示内容可以为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;
}

我知道它只是一个警告,不影响流程。但是我有什么办法可以修复它吗?

我认为这个新功能中存在一个应该被修复的错误。


警告是因为您有Content?泛型类型参数。您可以尝试使接口声明可为空,例如IStoreProcedure<Result?, Schema> - Pavel Anikhouski
@PavelAnikhouski 我试过了,但是它出现了错误。 - Maddie
尝试将 Content? 转换为 Content - Hadi Samadzad
@Hadi 是的,我可以做到。但是如果我们想忽略它,那使用可空引用类型还有什么意义呢? - Maddie
@Maddie,你能分享完整的代码示例吗?因为我无法重现你的问题。 - Pavel Anikhouski
@PavelAnikhouski 这是一个大项目,我不能分享整个代码。但我在我的问题中添加了一些更多的行。 - Maddie
1个回答

0

看起来这就是你想要的语法:

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

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


我不想显示它是“非空”的。相反,返回类型可以为null,但它不允许我指示。因此,当我在项目的其他部分中使用它时,无法将其返回类型用作可为空。 - Maddie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接