当达到三元运算符的 "other side" 时什么也不做?

Do nothing when "other side" of ternary operator is reached?

注意:我以前有时会看到这个问题 (, b, c),但这些都不是在 C# 中,也没有帮助。

假设我像这样使用 ? : 三元运算符(在 false 情况下什么也不做):

r==5? r=0 : <nothing> ;

我遇到了一个错误。把东西放在那里显然会解决问题。 我怎么能在不做一些随机空函数的情况下仍然让另一边空着呢?

你不能。条件 ?: 运算符的全部要点在于它计算 expression。你甚至不能只使用:

Foo() ? Bar() : Baz();

... 因为那不是声明。你必须对结果做一些事情......就像你访问 属性 一样。

如果您只想在满足特定条件时执行一段代码,那么 ?: 运算符不是您想要的 - 您需要一个 if 语句:

if (foo)
{
    bar();
}

就这么简单。不要试图将条件运算符扭曲成它不应该成为的东西。

当您显然需要两个参数时,为什么要使用 三进制?您可以简单地使用 if 语句:

 if(Condition())Action();

其他答案是正确的,但他们遗漏了一个关键点,我认为这是您遇到问题的主要问题。需要注意的是

r = 0

除了分配 r 一个值外,return 也是相同的值。你可以把它想象成一个函数。你可以调用一个函数,除了 returning 一个你可能会或可能不会使用的值之外,它可能会做一些其他的事情。

举个例子:

int square(int n)
{
    // Now you can do other things here too. Maybe you do something with the UI in here:
    Console.WriteLine("Calculating...");
    // ^ Now thing of the above code as assigning a value to a variable.
    return n * n;
    // But after assigning the value, it also returns the value...
}

所以,现在假设您可能有两种使用情况:

var x = square(2);
// -- OR --
square(2);

请注意,这两个语句输出 'Calculating...' 但前者将 2 * 24 的值分配给 x

更好的是,假设我们有一个函数:

int AssignValueToVariable(out int variable, int value)
{
    variable = value;
    return value;
}

现在这个函数显然是多余的,但让我们假设我们可以使用它来更好地理解。假设它等同于赋值运算符=.

也就是说,我们可以回到我们的场景。三元运算符 <condition> ? <true expression> : <false expression> 根据指定条件将两个表达式取入 return 。所以,当你写:

r == 5 ? r = 0 : r = 2; // Let's suppose the third operand to be r = 2

相当于:

r == 5 ? AssignValueToVariable(r, 0) : AssignValueToVariable(r, 2)

两者本质上是:

r == 5 ? 0 : 2

这带回了硬性规定,即操作数必须是表达式,因为整个事情必须归结为一个表达式。因此,您可以通过使用表达式的默认值获得 'nothing' 等价物。

或者,正如其他答案提到的那样,使用 if 语句,直接而简单:

if (r == 5)
    r = 0;

根据您提供的代码推断,我猜您是在用求值表达式做一些事情。您可以将值存储在一个单独的变量 result 中并用它做任何事情:

int result;
if (r == 5)
    result = r = 0; // This sets the value of both result and r to 0

现在,您可以用 result 替换您之前想要的表达式,即 r == 5 ? r = 0 : <nothing> // Pseudo-code.

希望对您有所帮助:)

我可以建议这样的扩展方法:

public static T ChangeOn<T>(this T variable, bool condition, T newValue)
{
    return condition ? newValue : variable;
}

并像这样使用它:

var result = r.ChangeOn(r == 5, 0);
//or: r = r.ChangeOn(r == 5, 0); for self change

如果您确实愿意,现在可以使用 Discard 运算符实现此目的。

public class Program
{
    public static void Main()
    {
        int r=5;
        _ = r==5 ? r=0 : 0;
        Console.WriteLine($"{r}");
        // outputs 0
    }
}

您现在也可以

_=Foo() ? Bar() : Baz();

只要Bar和Baz return同款或可换款即可。

只需将 undefined 传递给您不想对其进行任何操作的一侧即可。

// An array of numbers
let test = [12, 929, 11, 3]

// Adds 100 to the element in the text array if it is divisible by 3.
test.forEach(function (element, index) {
  element % 3 ? undefined : test[index] += 100;
});

// Logs the test array to the screen
console.log(test);

Passing "undefined" to the side of the ternary expression you want to disregard does exactly that.