有没有办法不从三元运算符的最后部分返回值

发布于 2024-12-20 00:21:17 字数 350 浏览 0 评论 0原文

有没有办法让三元运算符执行与此相同的操作?:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

叹梦 2024-12-27 00:21:17

这毫无意义。

三元运算符是一个表达式。
表达式必须始终有一个值,除非表达式用作语句(其中三元运算符不能)。

你不能写 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

美羊羊 2024-12-27 00:21:17

这与您完成与 IF 语句相同的任务最接近,只是您必须存储三元表达式的结果;即使你并没有真正使用它......

完整的例子:

namespace Blah
{
public class TernaryTest
{
public static void Main(string[] args)
{
bool someBool = true;
string someString = string.Empty;
string someValue = "hi";
object result = null;

// if someBool is true, assign someValue to someString,
// otherwise, effectively do nothing.
result = (someBool) ? someString = someValue : null;
} // end method Main
} // end class TernaryTest
} // end namespace Blah 

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:

namespace Blah
{
public class TernaryTest
{
public static void Main(string[] args)
{
bool someBool = true;
string someString = string.Empty;
string someValue = "hi";
object result = null;

// if someBool is true, assign someValue to someString,
// otherwise, effectively do nothing.
result = (someBool) ? someString = someValue : null;
} // end method Main
} // end class TernaryTest
} // end namespace Blah 
沉溺在你眼里的海 2024-12-27 00:21:17

我认为您正在寻找类似于使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文