【问题标题】:Is there a way to not return a value from last part of a ternary operator有没有办法不从三元运算符的最后一部分返回值
【发布时间】:2011-12-06 06:04:26
【问题描述】:

有没有办法让三元运算符做同样的事情?:

if (SomeBool)
  SomeStringProperty = SomeValue;

我可以这样做:

SomeStringProperty = someBool ? SomeValue : SomeStringProperty;

但是即使 SomeBool 为假(对),这也会触发 SomeStringProperty 的 getter 和 settor?所以和上面的说法不一样。

我知道解决方案是不使用三元运算符,但我只是想知道是否有办法忽略表达式的最后一部分。

【问题讨论】:

  • 如果将SomeStringProperty = 替换为Console.WriteLine( 会怎样?
  • 这就像问“我可以使用减法运算符来除吗?”
  • 三元运算符不是问题。问题是您想要抑制与三元运算符无关的 assignment 操作。而抑制赋值操作的方法就是不执行赋值。

标签: c# .net ternary


【解决方案1】:

这毫无意义。

三元运算符是一个表达式。
表达式必须总是有一个值,unless the expression is used as a statement(三元运算符不能)。

你不能写SomeProperty = <i>nothing</i>

【讨论】:

  • @HenkHolterman:我不是说Nothing 作为关键字;我的意思是 nothing 不改变价值。
  • 我知道,SomeProperty = ; 可能更清楚。但是 C# 确实有void expressions。所以一个表达式并不总是必须有一个值。但在?: 他们确实必须这样做。
【解决方案2】:

这与完成 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 

【讨论】:

    【解决方案3】:

    我认为您正在寻找类似 C# 三元运算符的短路评估 (http://en.wikipedia.org/wiki/Short-circuit_evaluation)。

    相信您会发现答案是否定的。

    与否决它的人相比,我认为这是一个有效的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 2014-09-24
      • 2014-12-03
      • 1970-01-01
      • 2023-01-07
      相关资源
      最近更新 更多