[英]Cannot convert null literal to non-nullable reference type
Using C# 10 I have the interface:使用 C# 10 我有界面:
public interface IPluralRuleProvider {
Boolean TryGetRule(CultureInfo culture, out PluralizationRuleDelegate rule);
}
In a class I am implementing the method and I have:在 class 中,我正在实施该方法并且我有:
Rules = new Dictionary<String, PluralizationRuleDelegate>();
Boolean IPluralRuleProvider.TryGetRule(CultureInfo culture, out PluralizationRuleDelegate rule)
{
rule = null;
if (Rules.TryGetValue(culture.Name, out rule))
return true;
if (culture.Parent != null && Rules.TryGetValue(culture.Parent.Name, out rule))
return true;
return false;
}
I am getting the warnings:我收到警告:
Cannot convert null literal to non-nullable reference type无法将 null 文字转换为不可为 null 的引用类型
Possible null reference assignment可能的 null 参考分配
I have been trying different versions but I always get some kind of warning.我一直在尝试不同的版本,但总是收到某种警告。
Can I change something to avoid this?我可以改变一些东西来避免这种情况吗?
TryGetRule
returns false
that the out rule
parameter will be assigned to null
.我假设当TryGetRule
返回false
时, out rule
参数将分配给null
。
out PluralizationRuleDelegate rule
: ...在这种情况下,您需要向out PluralizationRuleDelegate rule
添加两个注释:
PluralizationRuleDelegate?
- ie " rule
can be null
". - 即“ rule
可以是null
”。[NotNullWhen(true)]
- ie "Even though we've declared rule
as maybe- null
, we pinky-swear promise that when this method returns true
that the out rule
parameter will not be null
. [NotNullWhen(true)]
- 即“即使我们已将rule
声明为 maybe- null
,我们小指发誓 promise 当此方法返回true
时, out rule
参数将不是null
。
[NotNullWhen(true)]
postcondition - so be sure to double-check your logic - consider adding && rule != null
checks to every this.Rules.TryGetValue` call-site too.请注意,C# 编译器不会(我认为也不能?)详尽地证明您的[NotNullWhen(true)]
后置条件 - 因此请务必仔细检查您的逻辑 - 考虑添加&& rule != null
检查每个 this.Rules。 TryGetValue` 调用站点也是如此。 Anyway, change your interface
to this:无论如何,将您的interface
更改为:
using System.Diagnostics.CodeAnalysis;
public interface IPluralRuleProvider {
Boolean TryGetRule(CultureInfo culture, [NotNullWhen(true)] out PluralizationRuleDelegate? rule);
}
and implementation:和实施:
using System.Diagnostics.CodeAnalysis;
Boolean IPluralRuleProvider.TryGetRule(CultureInfo culture, [NotNullWhen(true)] out PluralizationRuleDelegate? rule) {
if (this.Rules.TryGetValue(culture.Name, out rule))
return true;
if (culture.Parent != null && this.Rules.TryGetValue(culture.Parent.Name, out rule))
return true;
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.