编辑
2025-09-27
C#
00

目录

摘要
中几种处理 null 的技术,并通过示例来说明它们的使用。
正文
1. Null 检查
2. 使用 ?. 和 ?? 运算符
3. Null 合并运算符 ??=
5. 使用默认值
6.使用 Null-coalescing 表达式和 switch 表达式

摘要

在 C# 开发中,处理 null 值是一个常见的任务。null 表示一个变量没有引用任何对象或值类型的默认值。不恰当的 null 值处理可能导致 NullReferenceException,这是常见的运行时错误之一。在这篇文章中,我们将探讨 C# 中几种处理 null 的技术,并通过示例来说明它们的使用。

正文

1. Null 检查

最基本的处理 null 的方法是在使用变量之前进行显式检查。

C#
static void Main(string[] args) { PrintName(null); } static void PrintName(string name) { if (name != null) { Console.WriteLine(name); } else { Console.WriteLine("Name is null!"); } }

image.png

2. 使用 ?.?? 运算符

C# 6.0 引入了空条件运算符 ?.,它允许你在访问成员之前检查对象是否为 null

C#
public void PrintLength(string str) { int? length = str?.Length; Console.WriteLine(length ?? 0); }

此外,?? 运算符允许你为可能为 null 的表达式提供一个默认值。

3. Null 合并运算符 ??=

C# 8.0 引入了 null 合并赋值运算符 ??=,它用于只在左侧操作数评估为 null 时才给它赋值。

C#
public void EnsureInitialized(ref string? text) { text ??= "Default Value"; }

4. C# 8.0 中的 Nullable Reference Types

C# 8.0 引入了可空引用类型,这允许开发者明确指出哪些变量可以为 null,从而提供更好的编译时检查。

C#
#nullable enable internal class Program { static void Main(string[] args) { PrintName("A"); } static void PrintName(string? name) { if (name is not null) { Console.WriteLine(name); } } }

image.png

5. 使用默认值

在某些情况下,为可能为 null 的变量提供一个默认值是有意义的。

C#
static void Main(string[] args) { Console.WriteLine(GetGreeting(null)); } static string GetGreeting(string? name) { // 如果name是空,返回Guest return $"Hello, {name ?? "Guest"}!"; }

image.png

6.使用 Null-coalescing 表达式和 switch 表达式

利用 null-coalescingswitch 进行更复杂的 null 检查。

C#
string str = null; string result = str switch { null => "Default value", _ => str }; Console.WriteLine(result); // 输出: Default value

以上示例展示了在C#中处理 null 的多种方法。通过合理运用这些方法,可以提高代码的健壮性,并减少异常发生的可能性。希望这些内容对你在处理 null 问题时有所帮助。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!