【发布时间】: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<Result?, Schema> -
@PavelAnikhouski 我试过但它给出了错误
-
尝试将
Content?转换为Content -
@Hadi 是的,我可以做到。但是,如果我们想随时忽略它,那么使用可为空的引用类型又有什么意义呢?
-
@Maddie 能否分享完整的代码示例,因为我无法重现您的问题
标签: c# c#-8.0 nullable-reference-types