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?;//表示可空的时间
相关推荐
晨星shine10 小时前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户2986985301418 小时前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户36674625267419 小时前
接口文档汇总 - 2.设备状态管理
c#
用户36674625267419 小时前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang2 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf5 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530145 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools6 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的6 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21886 天前
.NET 本地Db数据库-技术方案选型
windows·c#