c# ??=

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

例如:

复制代码
//当a不为空时返回a,为null时返回b
var c = a ?? b;

空合并赋值运算符??=,C# 8.0 及更高版本中可使用,该运算符仅在左侧操作数的求值结果为 null 时,才将其右侧操作数的值赋值给左操作数。 如果左操作数的计算结果为非 null,则 ??= 运算符不会计算其右操作数。

例如:

复制代码
List<int> numbers = null;
int? i = null;
 
numbers??= new List<int>();
numbers.Add(i ??= 17);
numbers.Add(i ??= 20);
 
Console.WriteLine(string.Join("", numbers));//output:17 17
Console.WriteLine(i);//output 17

?.不为null时执行后面的操作

例如:

复制代码
[Fact]
        public void UnitTest2()
        {
            var person = new Person();
            person.Name = person?.Code;
            //等价于
            person.Name = person == null ? null : person.Code;

            Person person2 = null;
            person2 ??= new Person();

            int num = (int)(person2?.Num);
            //等价于
            if (person2 != null)
            {
                num = person2.Num;
            }
            else
            {
                num = 0;
            }
        }

    public class Person
    {
        public string Name { get; set; }
        public string Code { get; set; }
        public int Num { get; set; }
    }

可空类型修饰符 ?,为了使值类型也能使用可空类型,就可以使用"?"来表示,表现形式为"T?"。T?是System.Nullable<T>的缩写,更便于读取。属于泛型的一种。例如:

复制代码
int i?;//表示可控的类型
DataTime time?;//表示可空的时间
相关推荐
艾莉丝努力练剑2 分钟前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
witton1 小时前
Go语言网络游戏服务器模块化编程
服务器·开发语言·游戏·golang·origin·模块化·耦合
枯萎穿心攻击2 小时前
ECS由浅入深第三节:进阶?System 的行为与复杂交互模式
开发语言·unity·c#·游戏引擎
Jerry Lau2 小时前
go go go 出发咯 - go web开发入门系列(一) helloworld
开发语言·前端·golang
nananaij2 小时前
【Python基础入门 re模块实现正则表达式操作】
开发语言·python·正则表达式
Micro麦可乐2 小时前
Java常用加密算法详解与实战代码 - 附可直接运行的测试示例
java·开发语言·加密算法·aes加解密·rsa加解密·hash算法
天下一般2 小时前
go入门 - day1 - 环境搭建
开发语言·后端·golang
雷羿 LexChien3 小时前
C++内存泄漏排查
开发语言·c++
小码编匠3 小时前
WPF 自定义TextBox带水印控件,可设置圆角
后端·c#·.net
水果里面有苹果3 小时前
17-C#的socket通信TCP-1
开发语言·tcp/ip·c#