C# 新特性 操做符單?與??和 ?. 的使用

1.單問號(?)html

1.1 單問號運算符能夠表示:可爲Null類型,C#2.0裏面實現了Nullable數據類型app

//A.好比下面一句,直接定義int爲null是錯誤的,錯誤提示爲沒法將null轉化成int,由於後者是不能夠爲null的值類型。
private int getNum = null;

//B.若是修改成下面的寫法就能夠初始指爲null,在特定狀況下?等同於基礎類型爲Nullable。
private int? getNum = null;
private Nullable<int> getNumNull = null;

2.雙問號(??)spa

?? 運算符稱爲 null 合併運算符,用於定義能夠爲 null 值的類型和引用類型的默認值。若是此運算符的左操做數不爲 null,則此運算符將返回左操做數;不然返回右操做數。.net

//A.定義getNum爲null,輸出結果爲0
private int? getNum = null;
Console.WriteLine(getNum ?? 0);

//B.定義getNum爲1,輸出結果爲1
private int getNum = 1;
Console.WriteLine(getNum ?? 0);

3. ?.若是爲空不報錯誤,不爲空原值輸出code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            myFun(null); // 123
            myFun("456");//  456

            Person personA = new Person() { name = "chenyishi" };
            Console.WriteLine(personA?.name);

            personA = null;
            Console.WriteLine(personA?.name);//person==null,仍不會報錯
        }


        static void myFun(string argA)
        {
            Console.WriteLine(argA ?? "123"); //argA==null,則輸出123
        }
    }

    class Person
    {
        public string name { get; set; }
    }
}

原文:htm

https://www.cnblogs.com/appleyrx520/p/7018610.htmlblog

https://www.cnblogs.com/chenyishi/p/8329752.htmlget

相關文章
相關標籤/搜索