空合并运算符和运算符 &&在 C# 中
是否可以在下一种情况下一起使用任何方式运算符 ??
和运算符 &&
:
bool? Any
{
get
{
var any = this.ViewState["any"] as bool?;
return any.HasValue ? any.Value && this.SomeBool : any;
}
}
这意味着下一步:
- 如果
any
为 null然后this.Any.HasValue
返回false
- 如果
any
有值,那么它会返回考虑另一个布尔属性的值,即Any & &一些布尔
Is it possible to use together any way operator ??
and operator &&
in next case:
bool? Any
{
get
{
var any = this.ViewState["any"] as bool?;
return any.HasValue ? any.Value && this.SomeBool : any;
}
}
This means next:
- if
any
is null thenthis.Any.HasValue
returnfalse
- if
any
has value, then it returns value considering another boolean property, i.e.Any && SomeBool
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我想知道为什么到目前为止没有人建议这样做:
都会返回
any
为 null,则无论this.SomeBool
的值是什么,null
是;true
如果any
和this.SomeBool
都为 true; 。any
不为 null,且this.SomeBool
为 false,则为false
I'm wondering why nobody has suggested this so far:
This returns
null
ifany
is null, no matter what the value ofthis.SomeBool
is;true
if bothany
andthis.SomeBool
are true; andfalse
ifany
is not null, andthis.SomeBool
is false.由于您希望在源为
null
的情况下返回null
,因此我认为??
不会帮助您将其写得更短或者更清楚。Since you want to return
null
in case the source isnull
, I don't think??
is going to help you write this any shorter or clearer.你是这个意思吗?
我将返回值保留为布尔值?但看起来它可以改为 bool。
这是这样测试的:
它返回
这里的行为与原始行为不太一样,因为应该返回 null 以使测试用例 1 和 4 相同。但也许这种行为不是必需的?
Is this what you mean?
I've left the return value as bool? but it looks like it could be changed to just bool.
This was tested like this:
which returns
The behaviour here is not quite the same as the original as null should be returned for test cases 1 and 4 to be identical. But maybe that behaviour isn't required?
Null Coalescing 运算符不适用于您构建方法逻辑的方式。当然你可以把它强行放在那里,但它看起来会很难看,而且只会让读它的人感到困惑。
我发现原始代码很难阅读和理解,因此重构并删除了三元运算符以揭示意图。
空合并只是很好的速记,应该明智地使用它
比以下内容更能揭示意图,并且更容易阅读和维护:
The Null Coalescing operator isn't going to work for how you've structured the logic for your method. Sure you could force it in there, but it's going to look ugly and just confuse whomever reads it.
I found the original code hard to read and understand, so refactored and removed the ternary operator to reveal intentions.
Null coalescing is just nice shorthand and should be used judiciously
Is more intention revealing, and easier to read + maintain than:
我认为你想要做的是这样的:
但是,我认为在这种情况下,使用 if 块可能更清楚:
如果有任何是
null
,那么你想返回true
或null
,对吗?I think what you're trying to do is this:
However, I think in cases like this, it's probably more clear to use an if block:
If any is
null
, then you want to returntrue
ornull
, right?问题是,你真的不想使用 ??操作员。它的目的是让您可以轻松避免空值,实际上您想保留空值。
thing is, you don't really want to use the ?? operator. Its meant to make it easy to avoid nulls, you actually want to keep nulls.
这具有您所描述的行为:
return (any ?? false) && this.SomeBool
This has the behavior you describe:
return (any ?? false) && this.SomeBool