• ?: 运算符(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;//第一个是有值的判断
  • 相关阅读:
    django控制台输出sql日志
    Find概述
    命令大全
    京东智联云在 Serverless 的探索
    如何优雅地部署一个 Serverless Next.js 应用
    腾讯云 Serverless 保障《创造营》硬糖少女 C 位出道
    Serverless 应用实践及典型案例解析
    LeetCode 数组:62. 不同路径(动态规划 带记忆的递归)
    LeetCode 数组:56.合并区间(数组的自带排序函数 区间合并问题)
    LeetCode 数组:162. 寻找峰值(二分法)
  • 原文地址:https://www.cnblogs.com/LessIsMoreZ/p/7402937.html
Copyright © 2020-2023  润新知