[英]Getting warning while using nullable reference type with a generic type
I have a generic type like the following, with a method named ExecuteAsync()
which can return an object or null
:我有一个像下面这样的泛型类型,有一个名为
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();
}
}
I use this in my service as follows:我在我的服务中使用它如下:
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;
}
}
If I don't add the ?
如果我不添加
?
in ContentService
to show that the content can be null
, I get this warning:在
ContentService
中显示内容可以为null
,我收到此警告:
I couldn't find a way to show that the content can be null
.我找不到一种方法来表明内容可以为
null
。 I can write it as follows, and it gets no warning, but it then assumes that the result value is not 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;
}
I know that it's just a warning and doesn't affect the process.我知道这只是一个警告,不会影响进程。 But is there anything that I can do to fix it?
但是我能做些什么来修复它吗?
I think it's a bug in this new feature that should be fixed.我认为这是这个新功能中的一个错误,应该修复。
Looks like this is the syntax you're after:看起来这是您所追求的语法:
public interface IStoreProcedure<Result, Schema>
where Result : IBaseEntity?
where Schema : IBaseSchema {
Task<Result> ExecuteAsync(Schema model);
}
It seems that by default, in a nullable context, a type constraint implies non-nullability, so to get nullability you have to add ?
似乎默认情况下,在可空上下文中,类型约束意味着不可空性,因此要获得可空性,您必须添加
?
to the type constraint.到类型约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.