.NET 帮助

C#空条件运算符(开发人员如何使用)

发布 2024年三月6日
分享:

C# Null 条件运算符为处理代码中的空值提供了一种更简洁、更安全的方法。该操作符的优点在于它能简化空值检查,使代码更简洁、更易读。

让我们深入了解一下 空条件操作符 的工作原理、优点以及如何在项目中使用它。我们还将探讨 IronPDF 及其与 Null 条件运算符的用例。

什么是空条件操作符?

空条件运算符,由于与猫王的发型相似,常被称为 "猫王运算符"。 (?.)只有在对象不为空的情况下,才允许对该对象执行成员访问或方法调用。

如果对象为空,操作将返回空,而不是抛出空引用异常。这个操作符改变了开发人员的游戏规则,因为它大大减少了安全访问潜在空对象成员所需的代码量。

空条件操作符的基础知识

要理解空条件操作符,请参考公有类 Employee 的示例。该类可能具有 public string FirstNamepublic string LastName 等属性。在传统的 C# 代码中,访问可能为空的 Employee 对象的属性时,需要进行显式空检查以避免异常:

if (employee != null)
{
    var name = employee.FirstName;
}
if (employee != null)
{
    var name = employee.FirstName;
}
If employee IsNot Nothing Then
	Dim name = employee.FirstName
End If
VB   C#

不过,使用空条件操作符可以将其简化为一行:

var name = employee?.FirstName;
var name = employee?.FirstName;
Dim name = employee?.FirstName
VB   C#

如果 employee 不为空,name 变量将接收 employee.FirstName 的值。如果 employee 为空,name 将被设置为空。因此,这一行代码就优雅地取代了多行显式空值检查。

使用空凝聚操作符进行组合

空条件操作符与 空凝聚赋值运算符 (??=).空值聚合运算符可让您在表达式求值为空时指定一个默认值。

例如,如果要确保 name 变量的默认值为 "未知 ",而不是 null,可以这样写

var name = employee?.FirstName ?? "Unknown";
var name = employee?.FirstName ?? "Unknown";
Dim name = If(employee?.FirstName, "Unknown")
VB   C#

这段代码检查 employee 是否为空,如果 employee.FirstName 为空,则将 "Unknown " 赋值给 name 。该代码在一次操作中优雅地处理了空值,展示了代码的简洁性和有效性。

C# 引入了可空类型,允许变量持有其基础类型的非空值或空值。

高级使用:空条件和集合

在处理集合时,可以使用空条件操作符访问元素,而不会出现空引用异常。假设您有一个雇员列表,并希望安全地访问第一个元素的名称。可以使用带方括号的操作符:

var firstName = employees?[0]?.FirstName ?? "Unknown";
var firstName = employees?[0]?.FirstName ?? "Unknown";
Dim firstName = If(employees?(0)?.FirstName, "Unknown")
VB   C#

这行代码是线程安全的,这意味着如果另一个线程在空值检查之后但在访问第一个元素之前将 employees 变为空值,你的代码也不会崩溃。在处理可归零类型时,了解其底层值类型非常重要,即与可归零类型相关联的不可归零类型。

线程安全和空条件操作符

使用空条件操作符的一个微妙之处在于它的线程安全特性。使用该操作符时,表达式的评估是线程安全的。这意味着,如果您访问的共享资源可能被其他线程修改,使用空条件操作符可以防止潜在的竞争条件。

不过,重要的是要明白,虽然操作符本身对其执行的操作是线程安全的,但并不能保证整个代码块或操作序列的线程安全。

实例

让我们来看一个更实际的例子:有一个对象可能会引发一个事件。在传统的 C# 中,为了避免出现空引用异常,我们会在调用事件之前检查事件处理程序是否为空:

if (PropertyChanged != null)
{
    PropertyChanged(this, new PropertyChangedEventArgs(name));
}
if (PropertyChanged != null)
{
    PropertyChanged(this, new PropertyChangedEventArgs(name));
}
If PropertyChanged IsNot Nothing Then
	PropertyChanged(Me, New PropertyChangedEventArgs(name))
End If
VB   C#

利用空条件运算符,可以简化为

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
If PropertyChanged IsNot Nothing Then
	PropertyChanged.Invoke(Me, New PropertyChangedEventArgs(name))
End If
VB   C#

这段简洁的代码实现了相同的结果,但可读性更高,也更安全。在需要明确返回 null 的情况下,可以简单地使用 `return null;` 语句。如果 PropertyChanged 为空,?. 操作符将使操作短路,从而防止出现异常。下面是完整的代码:

using System.ComponentModel;
public class Person : INotifyPropertyChanged
{
    private string name;
    public event PropertyChangedEventHandler PropertyChanged;
    public string Name
    {
        get { return name; }
        set
        {
            if (name != value)
            {
                name = value;
                OnPropertyChanged(nameof(Name));
            }
        }
    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        // Using the null conditional operator to safely invoke the event
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
class Program
{
    static void Main(string [] args)
    {
        Person person = new Person();
        person.PropertyChanged += (sender, e) =>
        {
            Console.WriteLine($"{e.PropertyName} property has changed.");
        };
        person.Name = "Iron Software"; // This will trigger the PropertyChanged event
    }
}
using System.ComponentModel;
public class Person : INotifyPropertyChanged
{
    private string name;
    public event PropertyChangedEventHandler PropertyChanged;
    public string Name
    {
        get { return name; }
        set
        {
            if (name != value)
            {
                name = value;
                OnPropertyChanged(nameof(Name));
            }
        }
    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        // Using the null conditional operator to safely invoke the event
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
class Program
{
    static void Main(string [] args)
    {
        Person person = new Person();
        person.PropertyChanged += (sender, e) =>
        {
            Console.WriteLine($"{e.PropertyName} property has changed.");
        };
        person.Name = "Iron Software"; // This will trigger the PropertyChanged event
    }
}
Imports System.ComponentModel
Public Class Person
	Implements INotifyPropertyChanged

'INSTANT VB NOTE: The field name was renamed since Visual Basic does not allow fields to have the same name as other class members:
	Private name_Conflict As String
	Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
	Public Property Name() As String
		Get
			Return name_Conflict
		End Get
		Set(ByVal value As String)
			If name_Conflict <> value Then
				name_Conflict = value
				OnPropertyChanged(NameOf(Name))
			End If
		End Set
	End Property
	Protected Overridable Sub OnPropertyChanged(ByVal propertyName As String)
		' Using the null conditional operator to safely invoke the event
		RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
	End Sub
End Class
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim person As New Person()
		AddHandler person.PropertyChanged, Sub(sender, e)
			Console.WriteLine($"{e.PropertyName} property has changed.")
		End Sub
		person.Name = "Iron Software" ' This will trigger the PropertyChanged event
	End Sub
End Class
VB   C#

下面是代码的输出结果:

C# Null 条件操作符(开发人员如何使用):图 1

C&num 中的 IronPDF 简介;项目

IronPDF 是一个面向 C# 开发人员的多功能库,允许您创建、编辑和 提取 PDF 在 .NET 应用程序中处理文档。由于其易用性以及将 PDF 功能无缝集成到任何 .NET 项目中的能力,该库非常出众。

IronPDF 的主要功能是转换 HTML 转 PDF,完整保留布局和样式。这是从网页内容生成PDF的绝佳解决方案,包括报告、发票和文档。它支持将HTML文件、URL和HTML字符串转换为PDF文件。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

无论是生成报告、发票,还是任何PDF格式的文档,IronPDF都提供了一整套工具来高效完成这些任务。

将 IronPDF 与空条件运算符整合在一起

将 IronPDF 与空条件运算符集成到项目中以处理 PDF,可显著增强应用程序的稳健性。在处理可能为空的 PDF 内容或执行可能导致空值的操作时,这种组合尤其有用。

让我们举一个简单的例子,使用 IronPDF 从 HTML 内容生成 PDF 文档。然后,我们将使用空条件操作符安全地访问文档的属性,说明如何优雅地处理空值。

安装 IronPDF

首先,您需要将 IronPDF 添加到您的项目中。您可以通过 NuGet 软件包管理器进行添加:

Install-Package IronPdf

现在,在 program.cs 文件中写入以下代码:

using IronPdf;
using System;
public class PdfGenerator
{
    public static void CreatePdf(string htmlContent, string outputPath)
    {
        // Instantiate the HtmlToPdf converter
        var renderer = new IronPdf.ChromePdfRenderer();
        // Generate a PDF document from HTML content
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        // Use the null conditional operator to safely access the document's properties
        var pageCount = pdfDocument?.PageCount ?? 0;
        // Check if the PDF was generated successfully and has pages
        if (pageCount > 0)
        {
            // Save the PDF document to the specified output path
            pdfDocument.SaveAs(outputPath);
            Console.WriteLine($"PDF created successfully with {pageCount} pages.");
        }
        else
        {
            // Handle cases where the PDF generation fails or returns null
            Console.WriteLine("Failed to create PDF or the document is empty.");
        }
    }
    public static void Main(string [] args)
    {
        // Define the HTML content for the PDF document
        string htmlContent = @"
            <html>
            <head>
                <title>Test PDF</title>
            </head>
            <body>
                <h1>Hello, IronPDF!</h1>
                <p>This is a simple PDF document generated from HTML using IronPDF.</p>
            </body>
            </html>";
        // Specify the path where the PDF document will be saved
        // Ensure this directory exists on your machine or adjust the path accordingly
        string filePath = @"F:\GeneratedPDF.pdf";
        // Call the method to generate and save the PDF document
        CreatePdf(htmlContent, filePath);
        // Wait for user input before closing the console window
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}
using IronPdf;
using System;
public class PdfGenerator
{
    public static void CreatePdf(string htmlContent, string outputPath)
    {
        // Instantiate the HtmlToPdf converter
        var renderer = new IronPdf.ChromePdfRenderer();
        // Generate a PDF document from HTML content
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        // Use the null conditional operator to safely access the document's properties
        var pageCount = pdfDocument?.PageCount ?? 0;
        // Check if the PDF was generated successfully and has pages
        if (pageCount > 0)
        {
            // Save the PDF document to the specified output path
            pdfDocument.SaveAs(outputPath);
            Console.WriteLine($"PDF created successfully with {pageCount} pages.");
        }
        else
        {
            // Handle cases where the PDF generation fails or returns null
            Console.WriteLine("Failed to create PDF or the document is empty.");
        }
    }
    public static void Main(string [] args)
    {
        // Define the HTML content for the PDF document
        string htmlContent = @"
            <html>
            <head>
                <title>Test PDF</title>
            </head>
            <body>
                <h1>Hello, IronPDF!</h1>
                <p>This is a simple PDF document generated from HTML using IronPDF.</p>
            </body>
            </html>";
        // Specify the path where the PDF document will be saved
        // Ensure this directory exists on your machine or adjust the path accordingly
        string filePath = @"F:\GeneratedPDF.pdf";
        // Call the method to generate and save the PDF document
        CreatePdf(htmlContent, filePath);
        // Wait for user input before closing the console window
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}
Imports IronPdf
Imports System
Public Class PdfGenerator
	Public Shared Sub CreatePdf(ByVal htmlContent As String, ByVal outputPath As String)
		' Instantiate the HtmlToPdf converter
		Dim renderer = New IronPdf.ChromePdfRenderer()
		' Generate a PDF document from HTML content
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
		' Use the null conditional operator to safely access the document's properties
		Dim pageCount = If(pdfDocument?.PageCount, 0)
		' Check if the PDF was generated successfully and has pages
		If pageCount > 0 Then
			' Save the PDF document to the specified output path
			pdfDocument.SaveAs(outputPath)
			Console.WriteLine($"PDF created successfully with {pageCount} pages.")
		Else
			' Handle cases where the PDF generation fails or returns null
			Console.WriteLine("Failed to create PDF or the document is empty.")
		End If
	End Sub
	Public Shared Sub Main(ByVal args() As String)
		' Define the HTML content for the PDF document
		Dim htmlContent As String = "
            <html>
            <head>
                <title>Test PDF</title>
            </head>
            <body>
                <h1>Hello, IronPDF!</h1>
                <p>This is a simple PDF document generated from HTML using IronPDF.</p>
            </body>
            </html>"
		' Specify the path where the PDF document will be saved
		' Ensure this directory exists on your machine or adjust the path accordingly
		Dim filePath As String = "F:\GeneratedPDF.pdf"
		' Call the method to generate and save the PDF document
		CreatePdf(htmlContent, filePath)
		' Wait for user input before closing the console window
		Console.WriteLine("Press any key to exit...")
		Console.ReadKey()
	End Sub
End Class
VB   C#

输出

下面是运行程序时的控制台输出:

C# Null 条件操作符(开发人员如何使用):图 2

这就是程序生成的 PDF 文件:

C# Null 条件操作符(开发人员如何使用):图 3

结论

C# Null 条件操作符(开发人员如何使用):图 4

在 C# 项目中将 IronPDF 与空条件运算符集成,可以大大简化 PDF 处理任务,同时确保代码安全,避免出现空引用异常。该示例展示了强大的 PDF 库与现代 C# 语言功能之间的协同作用,使您能够编写更简洁、更易维护的代码。

请记住,有效使用这些工具的关键在于了解它们的功能,并在项目中明智地应用它们。

IronPDF 为开发人员提供免费的 试用期 从 $749 开始,可持续获得全面支持和更新。

< 前一页
C# 集合(开发人员如何使用)
下一步 >
C# 线程睡眠方法(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >