我特别提请注意空传播,因为它与返回方法bool?
的使用有关。bool
例如,考虑以下情况:
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any();
}
这不会编译,并且存在以下错误:
不能隐式转换布尔?布尔值。存在显式转换(您是否缺少演员表)?
这意味着它将方法的整个主体视为 a bool?
,因此我假设我可以.GetValueOrDefault()
在 the 之后说,.Any()
但这不允许作为.Any()
return bool
not 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
.