跳過到頁腳內容
.NET幫助

C#可空類型(對開發者如何理解的工作)

使用 C# 工作時,您經常需要處理 空值,尤其是引用類型。C# 中的 Nullable 類型提供一種方式來表示值類型的未定義或不存在值。本指南涵蓋 C# nullable 類型的要點、實際用途,以及它們在不同情況下的運作方式。 我們稍後也會探討 IronPDF

Nullable Types in C#

根據預設,C# 中的值類型 (例如 int、bool、DateTime) 不能指定為空值。 為了解決這個限制,C# 引進了 nullable 值類型,讓您可以將 null 指定給值類型。當您需要表示沒有有效值時,Nullable 類型特別有用。

宣告可為空的類型

要在 C# 中宣告一個 nullable 類型,您可以使用下列語法:

// Declare a nullable integer
int? nullableInt = null;
// Declare a nullable integer
int? nullableInt = null;
' Declare a nullable integer
Dim nullableInt? As Integer = Nothing
$vbLabelText   $csharpLabel

這裡,int?Nullable<int> 的簡寫。 變數 nullableInt 可以儲存 int 值或 null。

檢查 null。

若要檢查可空類型變數是否有值,可以使用 HasValue 屬性,或直接將變數與 null 進行比較,如下所示:

if (nullableInt.HasValue)
{
    // If nullableInt has a value, print it
    Console.WriteLine("Value: " + nullableInt.Value);
}
else
{
    // If nullableInt does not have a value, print a message
    Console.WriteLine("No value assigned.");
}
if (nullableInt.HasValue)
{
    // If nullableInt has a value, print it
    Console.WriteLine("Value: " + nullableInt.Value);
}
else
{
    // If nullableInt does not have a value, print a message
    Console.WriteLine("No value assigned.");
}
If nullableInt.HasValue Then
	' If nullableInt has a value, print it
	Console.WriteLine("Value: " & nullableInt.Value)
Else
	' If nullableInt does not have a value, print a message
	Console.WriteLine("No value assigned.")
End If
$vbLabelText   $csharpLabel

另外,當 nullable 類型為 null 時,您也可以使用 null coalescing 運算符 (??) 來提供預設值:

// Assign 0 if nullableInt is null
int result = nullableInt ?? 0;
Console.WriteLine("Result: " + result);
// Assign 0 if nullableInt is null
int result = nullableInt ?? 0;
Console.WriteLine("Result: " + result);
' Assign 0 if nullableInt is null
Dim result As Integer = If(nullableInt, 0)
Console.WriteLine("Result: " & result)
$vbLabelText   $csharpLabel

如果 nullableInt 為空,則 result 將被賦予預設值 0。

可空值類型 vs 可空參考類型

在 C# 中,值類型(如 int、bool 和 double)與參考類型(如字串、物件)不同。 Nullable 值類型允許值類型表示 null,而 nullable 參考類型則允許參考類型預設為不可為空,從而降低出現 null 參考異常的風險。

可空值類型

nullable 值類型允許值類型接受 null 值。 若要宣告一個可為空的值類型,請在資料類型後面附加問號 ?

// Declare a nullable double
double? nullableDouble = null;
// Declare a nullable double
double? nullableDouble = null;
' Declare a nullable double
Dim nullableDouble? As Double = Nothing
$vbLabelText   $csharpLabel

在這個範例中,nullableDouble 可以儲存 double 值或 null。

可為空的參考類型

C# 8.0 引入了可空引用型別。您可以在專案層級啟用可空引用類型,也可以在程式碼檔案開頭新增 #nullable enable 指令。啟用可空引用類型後,必須使用 ? 明確地將引用類型標記為可空,這有助於避免由空引用引起的運行時異常。

#nullable enable
// Declare a nullable string
string? nullableString = null;
#nullable enable
// Declare a nullable string
string? nullableString = null;
'INSTANT VB TODO TASK: There is no equivalent to #nullable in VB:
'#nullable enable
' Declare a nullable string
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: string? nullableString = null;
Dim nullableString As String = Nothing
$vbLabelText   $csharpLabel

這裡,nullableString 允許為空。 如果您聲明一個不可空引用型別而沒有使用 ?,編譯器在偵測到潛在的空賦值時會發出警告。

啟用 Nullable 參考類型

若要在專案中全域啟用可空引用類型,請將以下行新增至您的 .csproj 檔案:

<Nullable>enable</Nullable>
<Nullable>enable</Nullable>
XML

啟用後,編譯器預設會將參考類型視為不可歸空。 此功能特別方便在編譯時而非執行時捕捉 null reference 問題。

實用範例

讓我們探討一些實例來鞏固您對 nullable 類型的理解。

範例 1:具有值類型的 Nullable 類型

在這個範例中,我們將使用 int 的 nullable 類型:

class Program
{
    static void Main(string[] args)
    {
        int? nullableInt = null;
        // Use null coalescing operator to assign a default value
        int b = nullableInt ?? 10;
        Console.WriteLine("b: " + b);
        if (nullableInt.HasValue)
        {
            // nullableInt has a value
            Console.WriteLine("nullableInt has value: " + nullableInt.Value);
        }
        else
        {
            // nullableInt is null
            Console.WriteLine("nullableInt is null");
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        int? nullableInt = null;
        // Use null coalescing operator to assign a default value
        int b = nullableInt ?? 10;
        Console.WriteLine("b: " + b);
        if (nullableInt.HasValue)
        {
            // nullableInt has a value
            Console.WriteLine("nullableInt has value: " + nullableInt.Value);
        }
        else
        {
            // nullableInt is null
            Console.WriteLine("nullableInt is null");
        }
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim nullableInt? As Integer = Nothing
		' Use null coalescing operator to assign a default value
		Dim b As Integer = If(nullableInt, 10)
		Console.WriteLine("b: " & b)
		If nullableInt.HasValue Then
			' nullableInt has a value
			Console.WriteLine("nullableInt has value: " & nullableInt.Value)
		Else
			' nullableInt is null
			Console.WriteLine("nullableInt is null")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

這裡,nullableInt 是一個可為空的 int 類型變數。 如果 nullableInt 為空,則由於空值合併運算符,b 將獲得值 10。 否則,b 的值將取 nullableInt 的值。

範例 2:可歸空的參照類型

現在,讓我們來看看 nullable 參考類型是如何運作的:

#nullable enable
class Program
{
    static void Main()
    {
        string? nullableString = null;
        string nonNullableString = "Hello";
        // Use null coalescing operator to provide a default value for length
        Console.WriteLine(nullableString?.Length ?? 0);
        Console.WriteLine(nonNullableString.Length);
    }
}
#nullable enable
class Program
{
    static void Main()
    {
        string? nullableString = null;
        string nonNullableString = "Hello";
        // Use null coalescing operator to provide a default value for length
        Console.WriteLine(nullableString?.Length ?? 0);
        Console.WriteLine(nonNullableString.Length);
    }
}
'INSTANT VB TODO TASK: There is no equivalent to #nullable in VB:
'#nullable enable
Friend Class Program
	Shared Sub Main()
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: string? nullableString = null;
		Dim nullableString As String = Nothing
		Dim nonNullableString As String = "Hello"
		' Use null coalescing operator to provide a default value for length
		Console.WriteLine(If(nullableString?.Length, 0))
		Console.WriteLine(nonNullableString.Length)
	End Sub
End Class
$vbLabelText   $csharpLabel

在上面的程式碼中,nullableString 可以為空,空合併運算子確保如果它為空,則字串的長度預設為 0。

範例 3:嵌套的 Nullable 類型

C# 允許您宣告嵌套的 nullable 類型。例如

// Redundant, but syntactically valid
int? nestedNullableInt = null;
// Redundant, but syntactically valid
int? nestedNullableInt = null;
' Redundant, but syntactically valid
Dim nestedNullableInt? As Integer = Nothing
$vbLabelText   $csharpLabel

儘管嵌套的 nullable 類型看似多餘,但在 C# 中它們在語法上是有效的。 然而,實際上,嵌套的 nullable 類型並沒有提供任何額外的功能,也很少被使用。

空凝聚運算符號 (??)

null coalescing 運算符 (??) 經常與 nullable 類型一起使用,以便在 nullable 類型為 null 時提供預設值。 此運算符可避免明確的 if-else 檢查,從而簡化程式碼。

int? nullableValue = null;
// Assign -1 if nullableValue is null
int defaultValue = nullableValue ?? -1;
int? nullableValue = null;
// Assign -1 if nullableValue is null
int defaultValue = nullableValue ?? -1;
Dim nullableValue? As Integer = Nothing
' Assign -1 if nullableValue is null
Dim defaultValue As Integer = If(nullableValue, -1)
$vbLabelText   $csharpLabel

在這個例子中,如果 nullableValue 為空,則 defaultValue 將被賦值為 -1。否則,defaultValue 將取 nullableValue 的值。

編譯時錯誤和可歸零類型

啟用 nullable reference types 後,C# 在偵測到 null assignments 的潛在問題時,會在編譯過程中產生警告和錯誤。 這些編譯時錯誤有助於及早發現問題,使您的程式碼更穩健。

請考慮以下範例:

string? nullableString = null;
// This will produce a compiler warning because nullableString may be null
string nonNullableString = nullableString;
string? nullableString = null;
// This will produce a compiler warning because nullableString may be null
string nonNullableString = nullableString;
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: string? nullableString = null;
Dim nullableString As String = Nothing
' This will produce a compiler warning because nullableString may be null
Dim nonNullableString As String = nullableString
$vbLabelText   $csharpLabel

在這種情況下,將 nullableString 賦值給 nonNullableString 會產生編譯器警告,因為 nullableString 可能為空,將其賦值給不可為空的類型可能會導致運行時異常。

使用 IronPDF 的可空類型

C# Nullable Types (How It Works For Developers):圖 1 - IronPDF:C# PDF Library

IronPDF 是一個 C# PDF 函式庫,旨在協助開發人員直接從 .NET 應用程式建立、編輯和處理 PDF 檔案。 您可以 將 HTML 轉換為 PDF、產生報告,甚至處理複雜的文件結構。

Nullable 類型在動態報表產生的情境中特別有用,例如當您為財務資料不完整的會計師產生 PDF 時。 透過使用 nullable 類型,您可以管理可選欄位、避免異常並提供預設值。

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        int? optionalIncome = null;  // Nullable type for optional income
        string? clientName = "Iron Dev";  // Nullable reference type for client name
        var renderer = new ChromePdfRenderer();
        string htmlContent = $@"
            <h1>Financial Report</h1>
            <p>Client Name: {clientName ?? "Unknown"}</p>
            <p>Income: {optionalIncome?.ToString() ?? "Data not available"}</p>";
        // Render the HTML to a PDF
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF to disk
        pdf.SaveAs("FinancialReport.pdf");
        Console.WriteLine("PDF Generated Successfully.");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        int? optionalIncome = null;  // Nullable type for optional income
        string? clientName = "Iron Dev";  // Nullable reference type for client name
        var renderer = new ChromePdfRenderer();
        string htmlContent = $@"
            <h1>Financial Report</h1>
            <p>Client Name: {clientName ?? "Unknown"}</p>
            <p>Income: {optionalIncome?.ToString() ?? "Data not available"}</p>";
        // Render the HTML to a PDF
        var pdf = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF to disk
        pdf.SaveAs("FinancialReport.pdf");
        Console.WriteLine("PDF Generated Successfully.");
    }
}
Imports IronPdf
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim optionalIncome? As Integer = Nothing ' Nullable type for optional income
'INSTANT VB WARNING: Nullable reference types have no equivalent in VB:
'ORIGINAL LINE: string? clientName = "Iron Dev";
		Dim clientName As String = "Iron Dev" ' Nullable reference type for client name
		Dim renderer = New ChromePdfRenderer()
		Dim htmlContent As String = $"
            <h1>Financial Report</h1>
            <p>Client Name: {If(clientName, "Unknown")}</p>ignoreignore<p>Income: {If(optionalIncome?.ToString(), "Data not available")}</p>"
		' Render the HTML to a PDF
		Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
		' Save the PDF to disk
		pdf.SaveAs("FinancialReport.pdf")
		Console.WriteLine("PDF Generated Successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

C# Nullable Types (How It Works For Developers):圖 2 - 範例程式碼輸出

這段程式碼中使用了可空類型(int?string?)來安全地處理缺失資料。 null coalescing 運算符 (??) 可確保如果有任何資料遺失,PDF 中會使用預設值。

結論

C# Nullable Types (How It Works For Developers):圖 3 - IronPDF 授權頁面

C# 中的可空類型是處理值類型和參照類型中的空值的強大工具。透過使用 nullable 類型,您可以避免 null reference 異常,並改善程式碼的穩健性。 請記住在新專案中啟用 nullable 參考類型,以受益於編譯時錯誤檢查,並在處理 nullable 類型時使用 null coalescing 運算符 (??) 來簡化您的程式碼。

IronPDF 提供 免費試用,幫助您在做出承諾之前探索其功能。 由於前期不需要任何費用,您可以先試水,看看它如何融入您的開發流程。 準備好繼續後,許可證從 $999 開始。

常見問題解答

如何在動態 PDF 生成中利用可空類型?

可空類型在動態 PDF 生成中可以至關重要,可以通過像 IronPDF 這樣的庫安全地表示可選字段。這確保了缺失的數據得到了適當處理,必要時提供了默認值。

在 C# 中聲明可空類型的語法是什麼?

在 C# 中,你可以通過在數據類型後附加一個問號 '?' 來聲明一個可空類型。例如,要聲明一個可空整數,你可以寫int? nullableInt = null;.

C# 中的可空類型會影響生成報告的健壯性嗎?

是的,使用可空類型可以增強生成報告的健壯性,確保可選字段的值缺失時不會引發錯誤。像 IronPDF 這樣的庫可以有效地利用可空類型來管理這些條件。

可空引用類型如何幫助防止運行時錯誤?

在 C# 8.0 中引入的可空引用類型允許引用類型默認為不可空,從而幫助防止運行時錯誤。這減少了空引用異常的風險,並允許在編譯過程中提前檢測潛在問題。

空合併運算符在管理可空類型中扮演什麼角色?

空合併運算符??用於管理可空類型,當可空類型為空時提供默認值。它簡化了代碼並有助於避免顯式的 if-else 檢查。

如何在 C# 中檢查可空類型是否有值?

在 C# 中,你可以使用HasValue屬性來檢查可空類型是否有值,或者直接將變量與 null 進行比較。

在 C# 應用中使用可空類型的一些典型場景是什麼?

可空類型通常用於數據可能不完整或可選的情境中,例如表單輸入、配置設置,或是在允許空值的數據庫接口中。它們在使用像 IronPDF 這樣的庫進行動態報告生成中特別有用。

啟用可空引用類型對 C# 專案的編譯有何影響?

在 C# 專案中啟用可空引用類型會對潛在的空引用問題發出編譯時警告和錯誤,從而提前捕獲問題並促進更健壯的代碼開發。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我