我有一个通用类型,像以下这样,拥有一个名为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](https://istack.dev59.com/HFhEW.webp)
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 AnikhouskiContent?
转换为Content
。 - Hadi Samadzad