我特别提请注意空传播,因为它与 bool?
有关以及 bool
的使用返回方法。例如,请考虑以下内容:
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any();
}
这不编译,并且存在以下错误:
Cannot implicitly convert bool? to bool. An explicit conversion exists (are you missing a cast)?
这意味着它将方法的整个主体视为 bool?
,因此我假设我可以说 .GetValueOrDefault()
在.Any()
之后但这是不允许的 .Any()
返回 bool
不是bool?
.
我知道我可以执行以下任一操作作为解决方法:
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any()
?? false;
}
或者
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
var any =
property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any();
return any.GetValueOrDefault();
}
或者
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any()
?? false;
}
我的问题是,为什么我不能直接调用.GetValueOrDefault()
链接到 .Any()
调用?
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return (property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any())
.GetValueOrDefault();
}
我认为这是有道理的,因为值实际上是 bool?
在这一点上而不是bool
.
最佳答案
?.
运算符之后的所有后续调用链都被解释为有条件的,而不仅仅是立即调用。所以,这段代码:
property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any()
解释为
property==null ? (bool?)null : property.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any()
如果添加 GetValueOrDefault()
:
property==null ? (bool?)null : property.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any()
.GetValueOrDefault()
它会失败,因为 Any()
返回 bool
而不是 bool?
。因此你需要在这里使用括号:
(property==null ? (bool?)null : property.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any())
.GetValueOrDefault()
使用 ?.
运算符时需要使用相同的括号:
(property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any())
.GetValueOrDefault()
关于c# - 为什么 null 传播不一致地传播 Nullable<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41755008/