zoukankan      html  css  js  c++  java
  • ?: 运算符(C# 参考)

    条件运算符 (?:) 根据 Boolean 表达式的值返回两个值之一。 下面是条件运算符的语法。

    condition ? first_expression : second_expression;  

    备注

    condition 的计算结果必须为 truefalse。 如果 condition 为 true,则将计算 first_expression 并使其成为结果。 如果 condition 为 false,则将计算 second_expression 并使其成为结果。 只计算两个表达式之一。
    first_expression 和 second_expression 的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换。

    总结:条件为true是,第一个是结果,条件为false时,第二个是结果

    你可通过使用条件运算符表达可能更确切地要求 if-else 构造的计算。 例如,以下代码首先使用 if 语句,然后使用条件运算符将整数分类为正整数或负整数。
    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";  
    条件运算符为右联运算符。 表达式 a ? b : c ? d : e 作为 a ? b : (c ? d : e)
    class ConditionalOp
    {
        static double sinc(double x)
        {
            return x != 0.0 ? Math.Sin(x) / x : 1.0;
        }
    
        static void Main()
        {
            Console.WriteLine(sinc(0.2));
            Console.WriteLine(sinc(0.1));
            Console.WriteLine(sinc(0.0));
        }
    }
    /*
    Output:
    0.993346653975306
    0.998334166468282
    1
    */

     我的示例:

     if (string.IsNullOrEmpty(tempIds))
    {
          tempIds = (Convert.IsDBNull(childDr["CRC_Id"]) ? "" : childDr["CRC_Id"].ToString());
          empNames = (Convert.IsDBNull(childDr["CRC_Name"]) ? "" : childDr["CRC_Name"].ToString());
          tempNumber = (Convert.IsDBNull(childDr["CRC_OfficeNumber"]) ? "" : childDr["CRC_OfficeNumber"].ToString());//第一个是为空的判断
    }

    或者
    dr["ProjectCode"] != DBNull.Value ? dr["ProjectCode"].ToString() : string.Empty;//第一个是有值的判断
  • 相关阅读:
    Google Maps 尝鲜
    ASDoc 的一些参数
    一本比较简单易懂的中文python入门教程
    word2010 2007中如何去掉首页页码
    转贴:关于出现java.lang.UnsupportedClassVersionError 错误的原因
    Windows下搭建SVN傻瓜式教程
    Red Hat中jdk1.6.0_03 tomcat6.0.35将hudson.war放入webapp后启动tomcat报错X connection to localhost:11.0 broken
    使用alternatives切换red hat linux的jdk版本
    linux安装ant 1.8.2
    反编译插件jadclips
  • 原文地址:https://www.cnblogs.com/LessIsMoreZ/p/7402937.html
Copyright © 2011-2022 走看看