C# 新特性 操作符单?与??和 ?. 的使用

Posted personblog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 新特性 操作符单?与??和 ?. 的使用相关的知识,希望对你有一定的参考价值。

1.单问号(?)

1.1 单问号运算符可以表示:可为Null类型,C#2.0里面实现了Nullable数据类型

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

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

2.双问号(??)

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

//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. ?.如果为空不报错误,不为空原值输出

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; 
    

原文:

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

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

以上是关于C# 新特性 操作符单?与??和 ?. 的使用的主要内容,如果未能解决你的问题,请参考以下文章

11年 C# 4.0四大新特性代码示例与解读

5、Redis6.0版的新特性

C# 10 新特性 —— 插值字符串优化

C# 动态编程新特性与DLR剖析

C#与C++的发展历程第一 - 由C#3.0起

C# 9 新特性 —— 增强的模式匹配