【问题标题】:c# Can someone explain this boolean logicc# 有人能解释一下这个布尔逻辑吗
【发布时间】:2010-09-07 09:19:59
【问题描述】:
// Example bool is true
bool t = true;

// Convert bool to int
int i = t ? 1 : 0;
Console.WriteLine(i); // 1

这会将 false 转换为 0,将 true 转换为 1,有人可以向我解释一下 t 是怎么回事吗? 1 : 0 有效吗?

【问题讨论】:

标签: c# asp.net boolean-logic


【解决方案1】:

看看Ternary Operator

int i = t ? 1 : 0;

等于:

if(t)
{
    i = 1;
}
else
{
    i = 0;
}

这种语法可以在多种语言中找到,甚至是 javascript。

如果你把冒号换成“否则”,可以把它想象成一个英文句子:

bool isItRaining = false;
int layersOfClothing = isItRaining? 2 otherwise 1;

【讨论】:

    【解决方案2】:

    这是C# Conditional Operator.

    i = does t == true? if yes, then assign 1, otherwise assign 0.
    

    也可以写成:

    if (t == true)
       t = 1;
    else 
       t = 0;
    

    if (t)
      t = 1;
    else
      t = 0;
    

    因为 t 为真,所以打印 1。

    【讨论】:

      【解决方案3】:

      如果 t equels true then i=1 else i=0

      ternary operator

      【讨论】:

        【解决方案4】:
        bool t= true;
        int i;
        
        if(t) 
        {
         i=1;
        }
        else
        {
         i=0;
        }
        

        更多请看?:运营商

        【讨论】:

          【解决方案5】:

          (? *) 这是条件运算符。

          条件运算符 (?:) 根据布尔表达式的值返回两个值之一。条件运算符的形式为

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

          在你的情况下 (true?1:0 ) 因为条件为真,这肯定是将 i 的值设置为 1。

          【讨论】:

            【解决方案6】:

            我相信编译器在内部会将语句内联为:

            Console.WriteLine(Convert.ToInt32(t));

            此 Convert.x 方法检查传递的参数是否为 true,否则返回 0。

            【讨论】:

              猜你喜欢
              • 2020-08-02
              • 2022-11-24
              • 2022-10-13
              • 2013-07-13
              • 2019-10-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-10-17
              相关资源
              最近更新 更多