IRONSOFTWAREHOME

C# 空条件操作符

[[academy-video-youtube({"vid":"eOpmjGF4qxo", "start_time":"0", "title":"C# 无条件操作符(? 操作员) 解释!, "创建者": "Gerald Versluis", "时长": "13分26秒"})]]

在他的一段视频中,Gerald Versluis 遇到了一个关于示例代码中问号 (?) 的问题。 这促使他制作了一个详细的视频,解释 C# 中的 null-conditional 运算符。 如果您曾好奇在C#中?[ ]的作用,Gerald的视频是一个非常好的资源,可以清楚地了解它。 让我们一步步来看看他的解释。

通过文档页面进行快速解释

Gerald 首先参考了微软关于成员访问操作符和表达式的官方文档。 他重点介绍了 C# 6 中引入的空条件运算符一节。在录制时,C# 9 是最新版本,C# 10 即将推出。

Gerald解释说,当您使用a为null,整个表达式将评估为null,而不是抛出NullReferenceException。 否则,将正常检索值。

虽然文档很有帮助,但 Gerald 更喜欢动手实践的例子,因此他转向了交互式编码环境。

示例:try.dot.net

为了演示,Gerald 切换到 try.dot.net,这是一个交互式 C# 环境。 他提到,该工具在 Blazor 上运行,允许用户直接在浏览器中执行 C# 代码。

他简要展示了 try.dot.net 中预载的默认斐波那契数列示例,然后清空该示例,开始一个以空条件运算符为重点的新示例。

全条件操作符解释

Gerald 创建了一个简单的 Person 类,该类具有以下属性:

public class Person
{
    // The Name property of the Person
    public string Name { get; set; }
    
    // A reference to another Person object representing the partner
    public Person Partner { get; set; }
    
    // An array representing the Person's hobbies
    public string[] Hobbies { get; set; }
}

他将Person对象初始化为null:

// Initialize a Person object as null
Person person = null;

// Attempting to access a property of a null object will throw a NullReferenceException
Console.WriteLine(person.Name);

运行此代码会抛出NullReferenceException,因为person为null。 为了防止出现这种情况,开发人员通常会在访问属性前添加空检查:

// Check if the person object is not null before accessing its properties
if (person != null)
{
    Console.WriteLine(person.Name);
}

这样做虽然可行,但会带来额外的代码行。 Gerald 解释了空条件运算符如何简化这一点:

// Using the null-conditional operator to safely access the Name property
Console.WriteLine(person?.Name);

现在,如果person为null,表达式简单地返回null而不是崩溃。

属性上的无条件操作符

Gerald通过设置一个Person对象来扩展这个例子:

// Create a new Person object
Person person = new Person { Name = "Gerald" };

// Access the Name property safely
Console.WriteLine(person?.Name);

由于person 不是null,它正确打印出**"Gerald"**。

接下来,他展示了一个嵌套示例:

// Safely access the Name property of the Partner object
Console.WriteLine(person?.Partner?.Name);

如果person.Partner 为null,整个表达式评估为null而不是抛出异常。 这样可以避免不必要的 "如果 "条件。

链式空条件操作符

Gerald 解释说,空条件运算符可以进行链式处理,从而在处理深嵌套对象时使代码更加简洁。 您可以使用以下方法来代替编写多个 null 检查:

// Chain null-conditional operators to safely access nested objects
Console.WriteLine(person?.Partner?.Name);

如果person.Partner 为null,结果将是null,以防止运行时错误。

数组上的无条件操作符

Gerald 将讨论扩展到 数组和集合。 他在 Person 类中添加了一个 Hobbies 数组,并演示了如何安全地访问元素:

// Safely access the first element of the Hobbies array
Console.WriteLine(person?.Hobbies?[0]);

在这里,如果Hobbies 为null,表达式将评估为null而不是导致异常。

结论

Gerald 的视频深入介绍了 C# 中的空条件运算符。 通过使用?[ ],开发者可以编写更简洁、安全的代码,避免NullReferenceException。 无论是处理属性、嵌套对象还是数组,空条件运算符都能使代码更加简洁易读。

如需完整演示,请务必查看 Gerald Versluis 的视频,他在视频中通过实际例子解释了一切!

Earn More by Sharing What You Love

Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Let's Stay in Touch!

Join our newsletter, you’ll get exclusive access on article updates. We value your privacy

Key in blue circle

立即获取免费的 30 天试用版密钥

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

OR
bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥
无需信用卡或创建账户