【问题标题】:Getting warning while using nullable reference type with a generic type将可空引用类型与泛型类型一起使用时收到警告
【发布时间】:2019-12-08 17:04:24
【问题描述】:

我有一个像下面这样的泛型类型,有一个名为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,我会收到以下警告:

我找不到显示内容可以是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&lt;Result?, Schema&gt;
  • @PavelAnikhouski 我试过但它给出了错误
  • 尝试将Content? 转换为Content
  • @Hadi 是的,我可以做到。但是,如果我们想随时忽略它,那么使用可为空的引用类型又有什么意义呢?
  • @Maddie 能否分享完整的代码示例,因为我无法重现您的问题

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


【解决方案1】:

看起来这是您所追求的语法:

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

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

【讨论】:

  • 我不想表明它“不为空”。恰恰相反。返回类型可以为 null,但它不允许我指出这一点。所以当我在项目的其他部分使用它时,我不能将它的返回类型用作可为空的。
猜你喜欢
  • 2015-09-12
  • 2022-01-23
  • 1970-01-01
  • 2021-08-09
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 2011-07-24
相关资源
最近更新 更多