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;//第一个是有值的判断
  • 相关阅读:
    Visual Studio 插件的开发
    EntityFramework 4.x 使用中遇到的问题 (2)
    F#学习笔记核心类型(二)
    F#学习笔记函数式编程(一)
    EntityFramework 4.x 使用中遇到的问题 (1)
    vue3项目一些小坑
    记一种拖拉拽编排流程的思路
    隐藏Jenkinsfile敏感信息
    Jenkins条件判断
    Jenkins 流水线语法自动部署
  • 原文地址:https://www.cnblogs.com/LessIsMoreZ/p/7402937.html
Copyright © 2011-2022 走看看