文章内容

2017/4/13 13:28:36,作 者: 黄兵

C#语法中一个问号(?)和两个问号(??)的运算符是什么意思?

(1)、C#语法中一个个问号(?)的运算符是指可以为 null 的类型。

 MSDN上面的解释:

在处理数据库和其他包含不可赋值的元素的数据类型时,将 null 赋值给数值类型布尔型以及日期类型的功能特别有用。例如,数据库中的布尔型字段可以存储值 true 或 false,或者,该字段也可以未定义。

 

 (2)、C#语法中两个问号(??)的运算符是指null 合并运算符,合并运算符为类型转换定义了一个预设值,以防可空类型的值为Null。

MSDN上面的解释:

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

?? 运算符称为 null 合并运算符,用于定义可以为 null 值的类型和引用类型的默认值。如果此运算符的左操作数不为 null,则此运算符将返回左操作数(左边表达式);否则当左操作数为 null,返回右操作数(右边表达式)。 


A nullable type can represent a value from the type’s domain, or the value can be undefined (in which case the value is null). You can use the ?? operator’s syntactic expressiveness to return an appropriate value (the right hand operand) when the left operand has a nullible type whose value is null. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

可空类型可以表示类型的域中的值,或者值可以是未定义的(在这种情况下,值为null)。 你可以使用?? 当左操作数具有值为null的无效类型时,操作符的句法表现能返回适当值(右手操作数)。 如果您尝试将nullable值类型分配给不可为空的值类型,而不使用? 运算符,您将生成编译时错误。 如果使用转换,并且可空值类型当前未定义,则将抛出InvalidOperationException异常。


C# Code:

int? x = null;//定义可空类型变量
int? y = x ?? 1000;//使用合并运算符,当变量x为null时,预设赋值1000

Console.WriteLine(y.ToString()); //1000

 

        /// <summary>
        /// Gets a single instance
        /// </summary>
        public static Log LogInstance
        {
              get

              {

                   return _log ?? (_log = new Log()); //如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。
               }
        }

代码实例:

 class NullCoalesce
    {
        static int? GetNullableInt()
        {
            return null;
        }

        static string GetStringValue()
        {
            return null;
        }

        static void Main()
        {
            int? x = null;

            // Set y to the value of x if x is NOT null; otherwise,
            // if x = null, set y to -1.
            int y = x ?? -1;

            // Assign i to return value of the method if the method's result
            // is NOT null; otherwise, if the result is null, set i to the
            // default value of int.
            int i = GetNullableInt() ?? default(int);

            string s = GetStringValue();
            // Display the value of s if s is NOT null; otherwise, 
            // display the string "Unspecified".
            Console.WriteLine(s ?? "Unspecified");
        }
    }
分享到:

发表评论

评论列表