具有泛型返回类型的可空引用类型 [英] Nullable reference types with generic return type
问题描述
我正在尝试使用新的 C# 8 可空引用类型功能,在重构我的代码时,我发现了这个(简化的)方法:
I'm playing around a bit with the new C# 8 nullable reference types feature, and while refactoring my code I came upon this (simplified) method:
public T Get<T>(string key)
{
var wrapper = cacheService.Get(key);
return wrapper.HasValue ? Deserialize<T>(wrapper) : default;
}
现在,这是一个警告
可能的空引用返回
这是合乎逻辑的,因为 default(T)
将为所有引用类型提供 null.一开始我以为我会改成下面这样:
which is logical, since default(T)
will give null for all reference types. At first I thought I would change it to the following:
公共T?获取
但这是做不到的.它说我要么必须添加一个通用约束 where T : class
或 where T : struct
.但这不是一个选项,因为它可以同时存在(我可以存储 int
或 int?
或 FooBar
的实例或任何缓存).我还读到了一个假设的新通用约束 where class?
但这似乎不起作用.
But this cannot be done. It says I either have to add a generic constraint where T : class
or where T : struct
. But that is not an option, as it can be both (I can store an int
or int?
or an instance of FooBar
or whatever in the cache).
I also read about a supposed new generic constraint where class?
but that did not seem to work.
我能想到的唯一简单的解决方案是使用空原谅运算符更改返回语句:
The only simple solution I can think of is changing the return statement using a null forgiving operator:
return wrapper.HasValue ? Deserialize<T>(wrapper) : default!;
但这感觉不对,因为它肯定可以为空,所以我在这里基本上是在对编译器撒谎..
But that feels wrong, since it can definitely be null, so I'm basically lying to the compiler here..
我该如何解决这个问题?我在这里遗漏了一些非常明显的东西吗?
How can I fix this? Am I missing something utterly obvious here?
推荐答案
你们很亲近.只需像这样编写您的方法:
You were very close. Just write your method like this:
[return: MaybeNull]
public T Get<T>(string key)
{
var wrapper = cacheService.Get(key);
return wrapper.HasValue ? Deserialize<T>(wrapper) : default!;
}
您必须使用 default!
来消除警告.但是你可以用 [return: MaybeNull]
告诉编译器它应该检查 null,即使它是一个不可为 null 的类型.
You have to use the default!
to get rid of the warning. But you can tell the compiler with [return: MaybeNull]
that it should check for null even if it's a non-nullable type.
在这种情况下,如果开发人员使用您的方法并且不检查 null,则他可能收到警告(取决于流分析).
In that case, the dev may get a warning (depends on flow analytics) if he uses your method and does not check for null.
有关详细信息,请参阅 Microsoft 文档:指定后置条件:MaybeNull 和 NotNull
For further info, see Microsoft documentation: Specify post-conditions: MaybeNull and NotNull
这篇关于具有泛型返回类型的可空引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!