I have a generic type like the following, with a method named ExecuteAsync()
which can return an object or 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:
I couldn't find a way to show that the content can be null
. I can write it as follows, and it gets no warning, but it then assumes that the result value is not 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.