有没有办法不从三元运算符的最后部分返回值
有没有办法让三元运算符执行与此相同的操作?:
if (SomeBool)
SomeStringProperty = SomeValue;
我可以这样做:
SomeStringProperty = someBool ? SomeValue : SomeStringProperty;
但是即使 SomeBool 为 false(正确),也会触发 SomeStringProperty 的 getter 和 settor?所以它不会与上面的说法相同。
我知道解决方案是不使用三元运算符,但我只是想知道是否有办法忽略表达式的最后一部分。
Is there a way to have the ternary operator do the same as this?:
if (SomeBool)
SomeStringProperty = SomeValue;
I could do this:
SomeStringProperty = someBool ? SomeValue : SomeStringProperty;
But that would fire the getter and settor for SomeStringProperty even when SomeBool is false (right)? So it would not be the same as the above statement.
I know the solution is to just not use the ternary operator, but I just got to wondering if there is a way to ignore the last part of the expression.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这毫无意义。
三元运算符是一个表达式。
表达式必须始终有一个值,除非表达式用作语句(其中三元运算符不能)。
你不能写
SomeProperty = nothing
That makes no sense.
The ternary operator is an expression.
An expression must always have a value, unless the expression is used as a statement (which the ternary operator cannot be).
You can't write
SomeProperty = nothing
这与您完成与 IF 语句相同的任务最接近,只是您必须存储三元表达式的结果;即使你并没有真正使用它......
完整的例子:
This is as close as you'll get to accomplishing the same as the IF statement, except that u must store the result of the ternary expression; even if u don't really use it...
Full example:
我认为您正在寻找类似于使用 C# 三元运算符进行短路评估 (http://en.wikipedia.org/wiki/Short-Circuit_evaluation) 的东西。
我相信你会发现答案是否定的。
与投反对票的人相比,我认为这是一个有效的问题。
I think you're looking for something like a short-circuit evaluation (http://en.wikipedia.org/wiki/Short-circuit_evaluation) with the C# ternary operator.
I believe you'll find that the answer is NO.
In contrast to whoever downvoted it, I think it is a valid question.