【问题标题】:Can anyone tell me what exactly this code means in c#?谁能告诉我这段代码在 c# 中到底意味着什么?
【发布时间】:2025-12-02 21:20:03
【问题描述】:

尤其是符号? : 以及如何以其他方式使用它们

Console.WriteLine("The rectangle with edges [{0},{1}] is {2}a square" ,
                r3.Edge1, r3.Edge2, (r3.IsSquare()) ? "" : "not ");

【问题讨论】:

  • 条件三元运算符
  • Short IF - ELSE statement的可能重复
  • 感谢所有的 cmets,伙计们!他们都非常有帮助!

标签: c#


【解决方案1】:

简单地说条件运算符(?)做following

如果条件是true,first_expression 被计算并成为结果。如果条件为false,则计算second_expression并成为结果

输入以下列格式给出,

条件?第一个表达式:第二个表达式;

在你的情况下,参数如下,

  condition  =  r3.IsSquare()  // <= return a Boolean I guess
  first_expression = ""    // Empty string
  second_expression = not  // word `not` 

那么在你的情况下,代码(r3.IsSquare()) ? "" : "not ") 做了什么,

  • 如果r3 是正方形,则输出为"",它是空字符串。
  • 如果r3 不是正方形,则输出单词not

请注意,在 r3 上调用的方法 IsSquare() 应该返回一个布尔值(真或假)。

在控制台程序上评估的相同条件,

    // if r3.IsSquare() return true
    Console.WriteLine((true ? "" : "not")); // <= Will out an empty
    // if r3.IsSquare() return false
    Console.WriteLine((false ? "" : "not")); // will out the word `not`

    Console.ReadKey();

【讨论】:

    【解决方案2】:

    正如其他人所说,?是一个三元运算符。

    所以要回答实际问题,

    Console.WriteLine("The rectangle with edges [{0},{1}] is {2}a square" ,
                    r3.Edge1, r3.Edge2, (r3.IsSquare()) ? "" : "not ");
    

    {0} 和 {1} 将分别替换为 r3.Edge1 和 r3.Edge2 的值,当该行写入控制台时。 r3.IsSquare() 很可能返回一个布尔值,所以如果它返回 true,它不会写任何东西(空字符串“”),但如果它返回 false,它会写“not”。

    例如,假设 r3.IsSquare() 返回 false,最终结果看起来像 The rectangle with edges[3, 6] is not a square,如果它返回 true,那么它会显示 The rectangle with edges[3, 6] is a square

    【讨论】:

      【解决方案3】:

      这是一个三元运算符。它的基本工作方式是这样的:

      bool thingToCheck = true;
      var x = thingToCheck ? "thingToCheck is true" : "thingToCheck is false";
      Console.WriteLine(x);
      

      MSDN reference

      【讨论】:

        【解决方案4】:

        看看MSDN

        简单示例

        int input = Convert.ToInt32(Console.ReadLine());
        string classify;
        
        // if-else construction.
        if (input > 0)
            classify = "positive";
        else
            classify = "negative";
        
        // ?: conditional operator.
        classify = (input > 0) ? "positive" : "negative";
        

        【讨论】:

          最近更新 更多