在任何情况下,c# 中的赋值运算符是否采用 bool 以外的任何其他值?

Does the assignment operator in c# take any other value other than bool in any scenario?

我最近开始学习 c# 并了解到 if 条件仅采用赋值运算符的布尔值,如下面的代码所示。但我想知道是否有任何情况下 if 取 bool 以外的任何值。

我尝试将 'a' 的类型更改为 char,但它给了我一个编译时错误。

Console.Write("Enter a character: ");
char c = (char)Console.Read();
bool a;
if (a=Char.IsLetter(c))
{
    if (a=Char.IsLower(c))
    {
        Console.WriteLine("The character is lowercase.");
    }
    else
    {
        Console.WriteLine("The character is uppercase.");
    }
}
else
{
    Console.WriteLine("Not a character");
}

But I wanted to know if there is any scenario where if takes any value other than bool.

不,不,有点

if-else (C# Reference)

An if statement identifies which statement to run based on the value of a Boolean expression

以下仅适用,因为结果是布尔值

if (a=Char.IsLower(c))

相当于

a=Char.IsLower(c);
if (a)

同下面ab成为结果Char.IsLower(c)

bool a = false;
bool b = false; 
a = b = Char.IsLower(c)

... 结果必须等于 bool(故事结束)

注意事项(如果你想这样称呼它的话)可以为 null 并且 解除运算符。提升运算符是通过 "lifting" 已经存在于不可空形式的运算符来处理可空类型的运算符,但是它仍然必须等同于布尔表达式。

?int bob = null

if(bob > 3) { ... }

其他资源

来自C# specs

12.4.8 Lifted operators

  • For the equality operators == !=

    • a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator considers two null values equal, and a null value unequal to any non-null value. If both operand are non-null, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.
  • For the relational operators < > <= >=

    • a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator produces the value false if one or both operands are null. Otherwise, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.

我有时会用这样的表达方式:-

string a = null;

    if((a = GetValue()) != null){
    DoSomething();
    }

分配 null 以外的其他值并检查它是否为布尔表达式是一种很好的语法。尽管请记住,最外面的括号将始终要求布尔表达式。