【C#】-对于Null值的处理方法

摘要


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

正文


1. Null 检查

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

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

2. 使用 ?.?? 运算符

C# 6.0 引入了空条件运算符 ?.,它允许你在访问成员之前检查对象是否为 null。本人最喜欢用的还是??

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

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

3. Null 合并运算符 ??=

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

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

4. C# 8.0 中的 Nullable Reference Types

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

#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);
        }
    }
}

5. 使用默认值

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

static void Main(string[] args)
{
    Console.WriteLine(GetGreeting(null));
}

static string GetGreeting(string? name)
{
    // 如果name是空,返回Guest
    return $"Hello, {name ?? "Guest"}!";
}

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

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

string str = null;

string result = str switch
{
    null => "Default value",
    _ => str
};

Console.WriteLine(result); // 输出: Default value

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

posted @   VisionCode  阅读(149)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.