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?;//表示可空的时间
相关推荐
唐青枫7 小时前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez201013 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5