.NET 幫助

C# Null 條件運算子(開發人員如何運作)

發佈 2024年3月6日
分享:

C# 的 Null 條件運算符提供了一種更簡潔且安全的方式來處理程式碼中的空值。這個運算符的優點在於它能夠簡化空值檢查,讓你的程式碼更乾淨且易讀。

讓我們深入了解如何使用這個 空條件運算子 運作方式、其優點,以及如何在您的專案中使用它。我們還將探討 IronPDF 以及其在使用空條件運算符時的用例。

什麼是空條件運算符?

空條件運算符,通常被稱為「Elvis 運算符」,因為它類似於 Elvis Presley 的髮型 (?.),允許您僅在對象不為 null 時對其進行成員訪問或方法調用。

如果對象為 null,操作將返回 null 而不是拋出空引用異常。這個運算符對開發人員來說是個劃時代的發明,因為它顯著減少了安全訪問可能為 null 對象的成員所需的代碼量。

Null 条件运算符的基础

要理解 null 条件运算符,请考虑 public class Employee 的例子。这个类可能有诸如 public string FirstNamepublic string LastName 这样的属性。在传统的 C# 代码中,访问一个可能为 null 的 Employee 对象的属性需要显式的 null 检查以避免异常:

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 設置為空。這一行代碼因此優雅地取代了多行明確的空值檢查。

結合 Null 合併運算符

當與 null 條件運算符結合時,null 條件運算符變得更加強大 空合併賦值運算子 (??=)空合併運算符讓您可以指定一個默認值,以防表達式的值為null。

例如,如果您想確保 name 變量有一個默認值 "Unknown" 而不是null,您可以這樣寫:

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

此程式碼檢查 employee 是否為 null,然後如果 employee.FirstName 為 null,將 "Unknown" 賦值給 name。它在一個操作中優雅地處理了空值,展示了您的程式碼如何變得精簡且高效。

C# 引入了可空類型,允許變數持有其基礎類型的非空值或 null。

高級用法:Null Conditional和集合

在處理集合時,可以使用null條件運算符來訪問元素,而不冒空引用異常的風險。假設你有一份員工名單並且想安全地訪問第一個元素的名字。你可以使用帶方括號的運算符:

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

這行代碼是線程安全的,這意味著它確保如果另一個線程在空檢查之後但在訪問其第一個元素之前將 employees 更改為 null,您的代碼不會崩潰。在處理可空類型時,了解其底層值類型非常重要,這是與可空類型關聯的不可空類型。

線程安全性及空條件運算符

使用空條件運算符的一個微妙之處是它的線程安全功能。當使用這個運算符時,表達式的評估是線程安全的。這意味著如果您正在訪問可能被另一個線程修改的共享資源,使用空條件運算符可以防止潛在的競爭條件。

然而,需要理解的是,儘管運算符本身對其執行的操作是線程安全的,但它不能保證整個代碼塊或操作序列的線程安全性。

實用範例

讓我們考慮一個更實用的範例,您有一個物件可能會引發事件。在傳統的 C# 中,您會在觸發事件之前檢查事件處理程序是否為 null,以避免 null 參考異常:

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 為 null 時會短路操作,從而防止異常。完整的代碼如下:

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# 空條件運算子(對開發人員的運作方式):圖 1

引導IronPDF在C#專案中

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# 空条件运算符(开发人员如何使用):图2

這是程式生成的 PDF:

C# Null 條件運算符(開發人員如何使用):圖 3

結論

C# 空條件運算子(對開發人員的運作方式):圖4

將 IronPDF 與 null 條件運算符整合到您的 C# 專案中,可以顯著簡化您的 PDF 處理任務,同時確保您的代碼免受 null 參考異常的影響。這個範例展示了一個強大的 PDF 庫與現代 C# 語言功能之間的協同作用,使您能夠編寫出更清晰、更易於維護的代碼。

請記住,有效使用這些工具的關鍵在於了解它們的功能並在您的專案中謹慎應用。

IronPDF 為開發人員提供了免費的 試用 從 $749 開始,提供持續的全面支持和更新。

< 上一頁
C# 集合(開發人員如何使用)
下一個 >
C# Thread Sleep 方法(對開發人員的運作方式)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >