C # New features single operator? And ?? and?. The use

1. Single question mark (?)

1.1 Single interrogation operator may be expressed: Null type may, C # 2.0 which implements Nullable data type

//A.比如下面一句,直接定义int为null是错误的,错误提示为无法将null转化成int,因为后者是不可以为null的值类型。
private int getNum = null;

//B.如果修改为下面的写法就可以初始指为null,在特定情况下?等同于基础类型为Nullable。
private int? getNum = null;
private Nullable<int> getNumNull = null;

2. Double question marks (??)

?? operator is called null merge operator, default values ​​are used to define a reference type and the type of null values. If the left operand of the operator is not null, then this operator returns the left operand; otherwise the right operand.

// A. defined getNum is null, the output is 0 
Private  int getNum =? Null ; 
Console.WriteLine (getNum ?? 0 ); 

// B. getNum defined as 1, the output of a 
Private  int getNum = 1 ; 
Console .WriteLine (getNum ?? 0 );

3.? If not reported error is empty, the original value of the output is not empty

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; }
    }
}

original:

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

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

Guess you like

Origin www.cnblogs.com/personblog/p/11105868.html