c# 可空 null ? ??

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {

            int? num = null;
            int a = num ?? -1; // ??  如果num 为null  分配-1  
            Console.WriteLine(a);

            // Is the HasValue property true?
            if (num.HasValue)
            {
                System.Console.WriteLine("num = " + num.Value);
            }
            else
            {
                System.Console.WriteLine("num = Null");
            }

            // y is set to zero
            int y = num.GetValueOrDefault(); // y=0;

            // num.Value throws an InvalidOperationException if num.HasValue is false
            try
            {
                y = num.Value;
            }
            catch (System.InvalidOperationException e)
            {
                System.Console.WriteLine(e.Message);
            }


            int? num1 = null;


            if (num1.HasValue)
            {
                Console.WriteLine("num" + num.Value);


            }
            else
            {

                Console.WriteLine("num=null");
            }

            int z = num1.GetValueOrDefault();
            try
            {
                z = num1.Value;
            }
            catch (Exception err)
            {

                Console.WriteLine(err.Message);
            }

        }
    }
}

可以为 null 的类型具有以下特性:

  • 可以为 null 的类型表示可被赋值为 null 值的值类型变量。 无法创建基于引用类型的可以为 null 的类型。 (引用类型已支持 null 值。)

  • 语法 T? 是 Nullable<T> 的简写,此处的 T 为值类型。 这两种形式可以互换。

  • 为可以为 null 的类型赋值的方法与为一般值类型赋值的方法相同,如 int? x = 10; 或 double? d = 4.108。 对于可以为 null 的类型,也可向其赋 null: int? x = null. 值

  • 如果基础类型的值为 null,请使用 Nullable<T>.GetValueOrDefault 方法返回该基础类型所赋的值或默认值,例如 int j = x.GetValueOrDefault();

  •  HasValue 和 Value 只读属性用于测试是否为空和检索值,如下面的示例所示:if(x.HasValue) j = x.Value;

    • 如果此变量包含值,则 HasValue 属性返回 true;或者如果是 null 则返回 false。

    • 如果已赋值,则 Value 属性返回该值。 否则,将引发 System.InvalidOperationException

    • HasValue 的默认值为 false。 Value 属性没有默认值。

    • 还可以将 == 和 != 操作数用于可为 null 的类型,如下面的示例所示:if (x != null) y = x;

  • 使用 ?? 算符分配默认值,在将当前值为 null 的可以为 null 的类型赋值给不可以为 null 的类型时,将应用该默认值,如 int? x = null; int y = x ?? -1;

  • 不允许使用嵌套的可以为 null 的类型。 将不编译下面一行:Nullable<Nullable<int>> n;

原文地址:https://www.cnblogs.com/xh0626/p/4860437.html