当前位置: 首页 > article >正文

理解C#中空值条件运算符及空值检查简化

前言

       .NET 4.6 及以上版本,提供了空值条件运算符 ?. 和 ?[]。这些运算符的引入,为我们提供了一种简明的方式来处理空值的场景、简化空值检查,可避免 NullReferenceExceptions 的异常。本文将探索 C# 的空值检查运算符。

介绍

         空值,这里指的是 null。在定义对象后,未对其声明或声明为 null。如下示例:


// 场景一
string productName = null;
// 场景二
Student student;

        下面通过一些示例来一起探索 C# 的空值条件运算符的使用方法与场景。

1、空值条件运算符 ?.

       空值条件运算符 ?. ,也称安全导航运算符。在我们使用它时,仅当对象非空时,它才允许您访问对象的成员。以下是它使用示例:

namespace Fountain.WinConsole.OtherDemo
{
    public class Student
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
        /// <summary>
        /// 班级
        /// </summary>
        public string Class { get; set; }
    }
}

using System;
namespace Fountain.WinConsole.OtherDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            #region 不使用空值条件运算符的情况
            Student student = GetStudent();
            // 使用 if 语句来判断对象是否为空。
            if (student != null)
            {
                // 
                student.Age = 21;
                // 输出
                Console.WriteLine(string.Format("学生年龄:{0}", student.Age));
            }
            // 使用 ?: 条件运算符的
            string studentName = (student == null) ? null : student.Name;
            #endregion

            #region 使用空值条件运算符的情况
            Student useStudent = GetStudent();
            // 如果 useStudent 为 null 则studentName为 null;
            string usestudentName = useStudent?.Name;
            // 输出 如果 useStudent 为 null 则输出空
            Console.WriteLine(string.Format("学生名称:{0}", usestudentName));
            // 输出 如果 useStudent 为 null 则输出空
            Console.WriteLine(string.Format("学生年龄:{0}", useStudent?.Age));
            #endregion
            Console.ReadLine(); 
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private static Student GetStudent()
        {
            Student student = new Student();
            student.Age = 16;
            student.Name = "诸事皆宜";
            return student; 
        }
    }
}

2、空索引条件运算符 ?[]

     它类似于 ?. 运算符,空索引条件运算符 ?[] 在索引到可能为空的集合时检查空值。

// 声明变量
List<Customer> customerList = new List<Customer>();
// 添加一个空对象
customerList.Add(null);
// 使用空值条件运算符的情况
string customerId = customerList?[0]?.CustomerID;
// 输出
Console.WriteLine(string.Format("customerId:{0}", customerId));

// 汇总金额
decimal SumAmounts(List<decimal[]> setsOfNumbers, int indexOfSetToSum)
{
    // 汇总List的值
    return setsOfNumbers?[indexOfSetToSum]?.Sum() ?? decimal.Zero;
}
// 传空List 调用 
var sumAmounts = SumAmounts(null, 0);
// 输出 0
Console.WriteLine(sumAmounts);

3、避免 NullReferenceExceptions

      空值条件运算符有助于防止未将对象引用设置到对象的实例的情况。( NullReferenceExceptions )

// 声明学生对象,将属性 Name 设为 null
Student student = new Student { Name = null };
// 抛出 NullReferenceException 异常
string city = student.Name; 
// 返回 null 
string nullableCity = student?.Name;

4、使用扩展方法的方式处理空值

      使用扩展方法也可以处理空值引用,但通过使用 ?. 进行空值条件检查,更为简化。

namespace Fountain.WinConsole.OtherDemo
{
    public class Student
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
        /// <summary>
        /// 班级
        /// </summary>
        public string Class { get; set; }
    }
}
//使用扩展方法也可以处理空值引用
public static class StudentExtensions
{
    public static int GetNameLength(this Student student)
    {
        return student == null ? -1 : student.Name.Length;
    }
}

using System;
namespace Fountain.WinConsole.OtherDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student person = null;
            // 通常 该方法将为空引用触发 并返回-1:
            int nameLength = person.GetNameLength(); 
            // 输出 -1
            Console.WriteLine(sumAmounts);
            Console.ReadLine(); 
        }
    }
}

小结

     以上是空值运算符 ?. 和 ?[] 的介绍内容,通过使用空值运算符对防止空引用异常和减少对显式空检查的需求,提高代码的可读性和安全性。在处理任何中间值可能为空值的复杂对象层次结构或集合时,特别有用。如有不到之处,请多多包涵。


http://www.kler.cn/news/361476.html

相关文章:

  • 《RECONX: RECONSTRUCT ANY SCENE FROM SPARSEVIEWS WITH VIDEO DIFFUSION MODEL》论文阅读
  • 【每日刷题】Day142
  • 【Unity】Unity中调用手机的震动功能 包括安卓和IOS
  • 10.22 MySQL
  • Java项目-基于springboot框架的学习选课系统项目实战(附源码+文档)
  • FineReport 数据筛选过滤
  • MySQL 中 LIKE 模糊查询如何优化?
  • 数据挖掘中的数据预处理:填充与主成分分析
  • OpenEuler2203编译安装Nginx1.24+ModSecurity(3.0.x)配置OWASP规则
  • 基于vue框架的的二手数码产品回收管理系统bodx1(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。
  • 《深度学习》YOLO v1网络架构 、损失值、NMS极大值抑制
  • GB/T28181-2022规范解读、应用场景和技术实现探究
  • C语言手撕链表,实现增删改查
  • 龙芯+FreeRTOS+LVGL实战笔记(新)——12按键输入初步
  • Spring Boot框架的大创项目文档管理系统
  • 【从零开始的LeetCode-算法】3184. 构成整天的下标对数目 I
  • Qt项目实战:图片轮播器
  • NC 单据模板自定义项 设置参照(自定义参照)
  • 【硬件问题】——显示器黑屏且只显示鼠标
  • 工具类的构造方法为什么要用private修饰
  • Linux安装最新docker(CentOS 7.6)
  • Github 2024-10-23C开源项目日报 Top10
  • 登录后端笔记(一):注册、登录;基于MD5加密
  • 思迅商云8采购单和批发单可以重复输入一样的货号,用于区别不同生产日期的同样商品的。
  • Java项目实战II基于Spring Boot的毕业就业信息管理系统设计与实现(源码+数据库+文档)
  • Spring Boot:为中小型医院网站提速