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?;//表示可空的时间
相关推荐
m2xgo5 分钟前
ThreadPoolexecutor源码分析、C++11线程池实现
开发语言·c++
工程师0077 分钟前
C# UI 跨线程刷新:Invoke/BeginInvoke 原理与封装
c#·invoke·begininvoke
@#¥&~是乱码鱼啦15 分钟前
AOP底层:动态代理执行流程(“断点之谜“)
java·开发语言
学困昇17 分钟前
彻底搞懂 Linux 基础 IO:文件描述符、重定向、dup2、缓冲区一次讲透!
linux·运维·服务器·开发语言·c++
源图客19 分钟前
Go语言goland代码编辑与调试
开发语言·后端·golang
froginwe1130 分钟前
R 绘图 - 饼图
开发语言
三十六煩惱風33 分钟前
2026-04/20~26技术问题整理
开发语言
杜子不疼.1 小时前
【C++ 在线五子棋对战】 - 项目介绍与环境搭建
开发语言·c++
50万马克的面包1 小时前
C 语言第18讲:预处理详解
c语言·开发语言·windows
码农刚子1 小时前
.NET 8 Web开发入门(二):C# 现代语法速成——为 Web API 量身定制
c#·.net