跳過到頁腳內容
.NET幫助

C# 模式匹配表達式(對於開發者的運行原理)

C# 的模式匹配是一個強大的功能,它在 C# 7.0 中引入,並在後續版本中進一步擴展。 它允許開發者在處理條件語句、類型檢查和對象解構時撰寫更簡潔和富有表現力的代碼。

模式匹配表達式提供了一種靈活且直觀的方法來將值與模式匹配並執行對應的代碼塊。 在本文中,我們將探討 C# 中模式匹配表達式的複雜性,包括語法、使用案例和代碼示例。 At the end of the article, we will also explore a bit about IronPDF PDF Generation Library from Iron Software to generate a PDF document on the fly in C# applications.

C# 中模式匹配的好處

C# 代碼中的模式匹配提供了以下眾多優勢:

  • 增強的可讀性:模式匹配簡化了複雜的條件邏輯,讓您的代碼更容易讓自己和其他開發者理解和跟隨。
  • 減少代碼行數:通過將錯綜複雜的條件語句壓縮成簡潔的模式,模式匹配有助於簡化您的代碼庫,導致代碼行數減少且實現更簡潔。
  • 提高可維護性:模式匹配所提供的清晰性促使代碼維護和調試變得更加容易。 由於模式明確劃分,因此更容易識別和修改特定的邏輯區塊,而不影響其餘代碼。
  • 更加表現力的算法:模式匹配讓開發者能夠以更自然更直觀的方式表達算法。 通過將代碼結構與問題解決範式對齊,模式匹配使得創建與其概念模型緊密像似的算法成為可能。

C# 中的模式匹配類型

模式匹配支持以下表達式:

  • is 表達式
  • switch 語句
  • switch 表達式

以下模式可用於與構造匹配:

聲明和類型模式

聲明和類型模式是 C# 中檢查表達式運行時類型與給定類型兼容性的重要工具。使用聲明模式,您可以同時檢查兼容性和聲明新的本地變量。 在此示例中,IronPDF用於將HTML內容呈現為PDF文檔,然後保存到指定位置。

object greeting = "Iron Software is Awesome!";
if (greeting is string message)
{
    Console.WriteLine(message.ToLower());  // output: iron software is awesome!
}
object greeting = "Iron Software is Awesome!";
if (greeting is string message)
{
    Console.WriteLine(message.ToLower());  // output: iron software is awesome!
}
Dim greeting As Object = "Iron Software is Awesome!"
Dim tempVar As Boolean = TypeOf greeting Is String
Dim message As String = If(tempVar, DirectCast(greeting, String), Nothing)
If tempVar Then
	Console.WriteLine(message.ToLower()) ' output: iron software is awesome!
End If
$vbLabelText   $csharpLabel

在此,聲明模式保證如果表達式 greeting 與類型 string 匹配,它會被分配給變量 message,以便進行後續操作。

當滿足以下條件之一時,聲明模式成立:

  • 表達式的運行時類型是 T
  • 表達式的運行時類型派生自 T,實現接口 T,或能夠隱式轉換為 T
  • 表達式的運行時類型是底層類型 T 的可空值類型。
  • 存在從表達式的運行時類型到 T 類型的拳空化或非拳空化轉換。

考慮以下示例來展示上述條件:

int? nullableX = 8;
int y = 45;
object boxedy = y;
if (nullableX is int a && boxedy is int b)
{
    Console.WriteLine(a + b);  // output: 53
}
int? nullableX = 8;
int y = 45;
object boxedy = y;
if (nullableX is int a && boxedy is int b)
{
    Console.WriteLine(a + b);  // output: 53
}
Dim nullableX? As Integer = 8
Dim y As Integer = 45
Dim boxedy As Object = y
Dim tempVar As Boolean = TypeOf boxedy Is Integer
Dim b As Integer = If(tempVar, DirectCast(boxedy, Integer), Nothing)
Dim tempVar2 As Boolean = TypeOf nullableX Is Integer
Dim a As Integer = If(tempVar2, CInt(nullableX), Nothing)
If tempVar2 AndAlso tempVar Then
	Console.WriteLine(a + b) ' output: 53
End If
$vbLabelText   $csharpLabel

此處,nullableX 匹配模式,因為它是一個底層類型為 int 的可空值類型,而 boxedy 匹配是因為它可以轉拳空到 int

當您只需要檢查表達式類型,而不聲明新變量時,您可以使用丢棄符 _,如下面示例所示:

public static decimal CalculateToll(Vehicle vehicle) => vehicle switch
{
    Bus _ => 4.00m,
    Motor _ => 8.50m,
    null => throw new ArgumentNullException(nameof(vehicle)),
    _ => throw new ArgumentException("Unknown type of a vehicle", nameof(vehicle)),
};
public static decimal CalculateToll(Vehicle vehicle) => vehicle switch
{
    Bus _ => 4.00m,
    Motor _ => 8.50m,
    null => throw new ArgumentNullException(nameof(vehicle)),
    _ => throw new ArgumentException("Unknown type of a vehicle", nameof(vehicle)),
};
'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'public static decimal CalculateToll(Vehicle vehicle) => vehicle switch
'{
'	Bus _ => 4.00m,
'	Motor _ => 8.50m,
'	null => throw new ArgumentNullException(nameof(vehicle)),
'	_ => throw new ArgumentException("Unknown type of a vehicle", nameof(vehicle)),
'};
$vbLabelText   $csharpLabel

在這段代碼中,_ 作為匹配任何類型 Vehicle 的佚名符。

聲明和類型模式確保.Expressions是在模式匹配之前非空的。 您可以使用否定的空常量模式檢查非空,如下所示:

if (inputVal is not null)
{
    // ...
}
if (inputVal is not null)
{
    // ...
}
If inputVal IsNot Nothing Then
	' ...
End If
$vbLabelText   $csharpLabel

這種否定方式保證 inputVal 在進行進一步操作之前是不為空的。

通過在您的 C# 代碼中利用聲明和類型模式,您可以加強可讀性,減少代碼行數,以及更有效地表達算法。 這些模式提供了一種簡潔和表現力的方式來處理基於類型的邏輯並改進代碼庫的可維護性。

常量模式

常量模式用於校驗表達式結果是否匹配特定常量值。 在此示例中,IronPDF用於將HTML內容呈現為PDF文檔,然後保存到指定位置。

public static decimal GetGroupTicketPrice(int visitorCount) => visitorCount switch
{
    1 => 2.0m,
    2 => 10.0m,
    3 => 25.0m,
    4 => 60.0m,
    0 => 0.0m,
    _ => throw new ArgumentException($"Not supported number of visitors: {visitorCount}", nameof(visitorCount)),
};
public static decimal GetGroupTicketPrice(int visitorCount) => visitorCount switch
{
    1 => 2.0m,
    2 => 10.0m,
    3 => 25.0m,
    4 => 60.0m,
    0 => 0.0m,
    _ => throw new ArgumentException($"Not supported number of visitors: {visitorCount}", nameof(visitorCount)),
};
Dim tempVar As Decimal
Select Case visitorCount
	Case 1
		tempVar = 2.0D
	Case 2
		tempVar = 10.0D
	Case 3
		tempVar = 25.0D
	Case 4
		tempVar = 60.0D
	Case 0
		tempVar = 0.0D
	Case Else
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: tempVar = throw new ArgumentException(string.Format("Not supported number of visitors: {0}", visitorCount), nameof(visitorCount));
		tempVar = throw New ArgumentException($"Not supported number of visitors: {visitorCount}", NameOf(visitorCount))
End Select
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'public static decimal GetGroupTicketPrice(int visitorCount)
'{
'	Return tempVar;
'}
$vbLabelText   $csharpLabel

此處,常量模式檢查 visitorCount 是否符合任何指定的常量值並返回對應票價。

在常量模式中,您可以使用各種類型的常量表達式,例如:

  1. 整數或浮點數字面值。
  2. 字符。
  3. 字符串字面值。
  4. 布爾值(truefalse)。
  5. 枚舉值。
  6. 已聲明的常量字段或本地名稱。
  7. null

類型為 Span<char>ReadOnlySpan<char> 的表達式可以匹配常量字符串。

要檢查 null,可以像這樣使用常量模式:

if (inputVal is null)
{
    return;
}
if (inputVal is null)
{
    return;
}
If inputVal Is Nothing Then
	Return
End If
$vbLabelText   $csharpLabel

這裡的模式保證 inputVal 確實為空後再繼續進行操作。

您還可以使用否定的空常量模式來確認非空值:

if (inputVal is not null)
{
    // ...
}
if (inputVal is not null)
{
    // ...
}
If inputVal IsNot Nothing Then
	' ...
End If
$vbLabelText   $csharpLabel

此模式驗證 inputVal 不為空,從而允許安全地進行後續操作。

通過在您的 C# 代碼中加入常量模式,您可以有效處理特定常量值需要匹配的情形,提升代碼的清晰度和可維護性。

關係模式

關係模式提供了一種將表達式結果與常數進行比較的方法。 在此示例中,IronPDF用於將HTML內容呈現為PDF文檔,然後保存到指定位置。

Console.WriteLine(Classify(20));  // output: Too high
Console.WriteLine(Classify(double.NaN));  // output: Unknown
Console.WriteLine(Classify(4));  // output: Acceptable

static string Classify(double measurement) => measurement switch
{
    < -4.0 => "Too low",
    > 10.0 => "Too high",
    double.NaN => "Unknown",
    _ => "Acceptable",
};
Console.WriteLine(Classify(20));  // output: Too high
Console.WriteLine(Classify(double.NaN));  // output: Unknown
Console.WriteLine(Classify(4));  // output: Acceptable

static string Classify(double measurement) => measurement switch
{
    < -4.0 => "Too low",
    > 10.0 => "Too high",
    double.NaN => "Unknown",
    _ => "Acceptable",
};
Console.WriteLine(Classify(20)) ' output: Too high
Console.WriteLine(Classify(Double.NaN)) ' output: Unknown
Console.WriteLine(Classify(4)) ' output: Acceptable

'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'static string Classify(double measurement) => measurement switch
'{
'	< -4.0 => "Too low",
'	> 10.0 => "Too high",
'	double.NaN => "Unknown",
'	_ => "Acceptable",
'};
$vbLabelText   $csharpLabel

在此,關係模式根據表達式 measurement 是否滿足特定閾值來確定其分類。

關係模式的右手邊必須是常量表達式,可以是整數、浮點數、charenum 類型。 左手邊可以使用 <><=>= 運算符。

要匹配某個範圍內的表達式結果,可以使用連接“與”模式,如下所示:

Console.WriteLine(GetCalendarSeason(new DateTime(2024, 3, 12)));  // output: spring
Console.WriteLine(GetCalendarSeason(new DateTime(2024, 7, 12)));  // output: summer
Console.WriteLine(GetCalendarSeason(new DateTime(2024, 2, 12)));  // output: winter

static string GetCalendarSeason(DateTime date) => date.Month switch
{
    >= 3 and < 6 => "spring",
    >= 6 and < 9 => "summer",
    >= 9 and < 12 => "autumn",
    12 or (>= 1 and <3) => "winter",
    _ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
};
Console.WriteLine(GetCalendarSeason(new DateTime(2024, 3, 12)));  // output: spring
Console.WriteLine(GetCalendarSeason(new DateTime(2024, 7, 12)));  // output: summer
Console.WriteLine(GetCalendarSeason(new DateTime(2024, 2, 12)));  // output: winter

static string GetCalendarSeason(DateTime date) => date.Month switch
{
    >= 3 and < 6 => "spring",
    >= 6 and < 9 => "summer",
    >= 9 and < 12 => "autumn",
    12 or (>= 1 and <3) => "winter",
    _ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
};
Console.WriteLine(GetCalendarSeason(New DateTime(2024, 3, 12))) ' output: spring
Console.WriteLine(GetCalendarSeason(New DateTime(2024, 7, 12))) ' output: summer
Console.WriteLine(GetCalendarSeason(New DateTime(2024, 2, 12))) ' output: winter

'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'static string GetCalendarSeason(DateTime date) => date.Month switch
'{
'	>= 3 and < 6 => "spring",
'	>= 6 and < 9 => "summer",
'	>= 9 and < 12 => "autumn",
'	12 or (>= 1 and <3) => "winter",
'	_ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
'};
$vbLabelText   $csharpLabel

該呈現描述了如何使用連接“與”模式來確定基於月份落在特定範圍內的日曆季節。 還提到關係模式提供了一種簡潔且表現力的手段來將表達式結果與常數進行比較,從而增強代碼的清晰度和可維護性。

丟棄模式

_ 代表的丟棄模式用於匹配任何表達式,包括 null。 請看以下示例:

Console.WriteLine(GetDiscountInPercent(DayOfWeek.Friday));  // output: 5.0
Console.WriteLine(GetDiscountInPercent(null));  // output: 0.0
Console.WriteLine(GetDiscountInPercent((DayOfWeek)10));  // output: 0.0

static decimal GetDiscountInPercent(DayOfWeek? dayOfWeek) => dayOfWeek switch
{
    DayOfWeek.Monday => 0.5m,
    DayOfWeek.Tuesday => 12.5m,
    DayOfWeek.Wednesday => 7.5m,
    DayOfWeek.Thursday => 12.5m,
    DayOfWeek.Friday => 5.0m,
    DayOfWeek.Saturday => 2.5m,
    DayOfWeek.Sunday => 2.0m,
    _ => 0.0m,
};
Console.WriteLine(GetDiscountInPercent(DayOfWeek.Friday));  // output: 5.0
Console.WriteLine(GetDiscountInPercent(null));  // output: 0.0
Console.WriteLine(GetDiscountInPercent((DayOfWeek)10));  // output: 0.0

static decimal GetDiscountInPercent(DayOfWeek? dayOfWeek) => dayOfWeek switch
{
    DayOfWeek.Monday => 0.5m,
    DayOfWeek.Tuesday => 12.5m,
    DayOfWeek.Wednesday => 7.5m,
    DayOfWeek.Thursday => 12.5m,
    DayOfWeek.Friday => 5.0m,
    DayOfWeek.Saturday => 2.5m,
    DayOfWeek.Sunday => 2.0m,
    _ => 0.0m,
};
Console.WriteLine(GetDiscountInPercent(DayOfWeek.Friday)) ' output: 5.0
Console.WriteLine(GetDiscountInPercent(Nothing)) ' output: 0.0
Console.WriteLine(GetDiscountInPercent(CType(10, DayOfWeek))) ' output: 0.0

Dim tempVar As Decimal
Select Case dayOfWeek
	Case DayOfWeek.Monday
		tempVar = 0.5D
	Case DayOfWeek.Tuesday
		tempVar = 12.5D
	Case DayOfWeek.Wednesday
		tempVar = 7.5D
	Case DayOfWeek.Thursday
		tempVar = 12.5D
	Case DayOfWeek.Friday
		tempVar = 5.0D
	Case DayOfWeek.Saturday
		tempVar = 2.5D
	Case DayOfWeek.Sunday
		tempVar = 2.0D
	Case Else
		tempVar = 0.0D
End Select
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static decimal GetDiscountInPercent(System.Nullable(Of DayOfWeek) dayOfWeek)
'{
'	Return tempVar;
'}
$vbLabelText   $csharpLabel

在上面的丟棄模式示例中,它處理了所有可能的輸入值。 一周的所有日期都得到了處理並提供了一個默認值。 通過這點,所有可能的值都被處理。 丟棄模式不能用作 is 表達式或 switch 語句中的模式。 在這種情況下,可以與丟棄符一起使用 var 模式,如 var _,以匹配任何表達式。 然而,丟棄模式在 switch 表達式中是被允許的。 相關細節可參見功能提案說明的丟棄模式部分。

邏輯模式

C# 中的邏輯模式提供了強大的模式匹配工具,包括否定、連接和析取,允許更靈活和富有表現力的匹配條件。

否定(not 模式)

否定模式由 not 表示,當否定模式不匹配表達式時匹配該表達式。 這尤其有用於檢查表達式是否非空,如下所示:

if (input is not null)
{
    // ...
}
if (input is not null)
{
    // ...
}
If input IsNot Nothing Then
	' ...
End If
$vbLabelText   $csharpLabel

此處,如果 input 不為空則執行代碼塊。

連接(and 模式)

連接模式使用 and 關鍵字,當兩個模式都匹配時會匹配表達式。 這允許合併多個條件,如以下示例所示:

Console.WriteLine(Classify(13));    // output: High
Console.WriteLine(Classify(-100));  // output: Too low
Console.WriteLine(Classify(5.7));   // output: Acceptable

static string Classify(double measurement) => measurement switch
{
    < -40.0 => "Too low",
    >= -40.0 and < 0 => "Low",
    >= 0 and < 10.0 => "Acceptable",
    >= 10.0 and < 20.0 => "High",
    >= 20.0 => "Too high",
    double.NaN => "Unknown",
};
Console.WriteLine(Classify(13));    // output: High
Console.WriteLine(Classify(-100));  // output: Too low
Console.WriteLine(Classify(5.7));   // output: Acceptable

static string Classify(double measurement) => measurement switch
{
    < -40.0 => "Too low",
    >= -40.0 and < 0 => "Low",
    >= 0 and < 10.0 => "Acceptable",
    >= 10.0 and < 20.0 => "High",
    >= 20.0 => "Too high",
    double.NaN => "Unknown",
};
Console.WriteLine(Classify(13)) ' output: High
Console.WriteLine(Classify(-100)) ' output: Too low
Console.WriteLine(Classify(5.7)) ' output: Acceptable

'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'static string Classify(double measurement) => measurement switch
'{
'	< -40.0 => "Too low",
'	>= -40.0 and < 0 => "Low",
'	>= 0 and < 10.0 => "Acceptable",
'	>= 10.0 and < 20.0 => "High",
'	>= 20.0 => "Too high",
'	double.NaN => "Unknown",
'};
$vbLabelText   $csharpLabel

在這個例子中,根據其值範圍對 measurement 進行了分類。

析取(or 模式)

析取模式使用 or 關鍵字,當任意一個模式匹配表達式時即可匹配該表達式。 這允許處理多種可能的條件,如下所示:

Console.WriteLine(GetCalendarSeason(new DateTime(2021, 1, 19)));  // output: winter
Console.WriteLine(GetCalendarSeason(new DateTime(2021, 10, 9)));  // output: autumn
Console.WriteLine(GetCalendarSeason(new DateTime(2021, 5, 11)));  // output: spring

static string GetCalendarSeason(DateTime date) => date.Month switch
{
    3 or 4 or 5 => "spring",
    6 or 7 or 8 => "summer",
    9 or 10 or 11 => "autumn",
    12 or 1 or 2 => "winter",
    _ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
};
Console.WriteLine(GetCalendarSeason(new DateTime(2021, 1, 19)));  // output: winter
Console.WriteLine(GetCalendarSeason(new DateTime(2021, 10, 9)));  // output: autumn
Console.WriteLine(GetCalendarSeason(new DateTime(2021, 5, 11)));  // output: spring

static string GetCalendarSeason(DateTime date) => date.Month switch
{
    3 or 4 or 5 => "spring",
    6 or 7 or 8 => "summer",
    9 or 10 or 11 => "autumn",
    12 or 1 or 2 => "winter",
    _ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
};
Console.WriteLine(GetCalendarSeason(New DateTime(2021, 1, 19))) ' output: winter
Console.WriteLine(GetCalendarSeason(New DateTime(2021, 10, 9))) ' output: autumn
Console.WriteLine(GetCalendarSeason(New DateTime(2021, 5, 11))) ' output: spring

Dim tempVar As String
Select Case [date].Month
	Case 3, 4, 5
		tempVar = "spring"
	Case 6, 7, 8
		tempVar = "summer"
	Case 9, 10, 11
		tempVar = "autumn"
	Case 12, 1, 2
		tempVar = "winter"
	Case Else
'INSTANT VB TODO TASK: Throw expressions are not converted by Instant VB:
'ORIGINAL LINE: tempVar = throw new ArgumentOutOfRangeException(nameof(date), string.Format("Date with unexpected month: {0}.", date.Month));
		tempVar = throw New ArgumentOutOfRangeException(NameOf([date]), $"Date with unexpected month: {[date].Month}.")
End Select
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'static string GetCalendarSeason(DateTime @date)
'{
'	Return tempVar;
'}
$vbLabelText   $csharpLabel

此處根據提供日期的月份來確定日曆季節。

這些模式組合器可以重複使用來創建更複雜和精確的匹配條件,增強代碼的靈活性和可讀性。

屬性模式

屬性模式允許將一個表達式的屬性或字段與嵌套模式進行匹配。 以下代碼片段展示了一個例子:

static bool IsConferenceDay(DateTime date) => date is { Year: 2020, Month: 5, Day: 19 or 20 or 21 };
static bool IsConferenceDay(DateTime date) => date is { Year: 2020, Month: 5, Day: 19 or 20 or 21 };
Shared Function IsConferenceDay(ByVal [date] As DateTime) As Boolean
'INSTANT VB TODO TASK: The following 'is' operator pattern is not converted by Instant VB:
	Return [date] is { Year: 2020, Month: 5, Day: 19 [or] 20 [or] 21 }
End Function
$vbLabelText   $csharpLabel

在此,屬性模式確保所提供的日期對應於指定的會議日之一。

您還可以在屬性模式中執行運行時類型檢查和變量聲明,如下所示:

static string TakeFive(object input) => input switch
{
    string { Length: >= 5 } s => s.Substring(0, 5),
    string s => s,
    ICollection<char> { Count: >= 5 } symbols => new string(symbols.Take(5).ToArray()),
    ICollection<char> symbols => new string(symbols.ToArray()),
    null => throw new ArgumentNullException(nameof(input)),
    _ => throw new ArgumentException("Unsupported input type."),
};
static string TakeFive(object input) => input switch
{
    string { Length: >= 5 } s => s.Substring(0, 5),
    string s => s,
    ICollection<char> { Count: >= 5 } symbols => new string(symbols.Take(5).ToArray()),
    ICollection<char> symbols => new string(symbols.ToArray()),
    null => throw new ArgumentNullException(nameof(input)),
    _ => throw new ArgumentException("Unsupported input type."),
};
'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'static string TakeFive(object input) => input switch
'{
'	string { Length: >= 5 } s => s.Substring(0, 5),
'	string s => s,
'	ICollection<char> { Count: >= 5 } symbols => new string(symbols.Take(5).ToArray()),
'	ICollection<char> symbols => new string(symbols.ToArray()),
'	null => throw new ArgumentNullException(nameof(input)),
'	_ => throw new ArgumentException("Unsupported input type."),
'};
$vbLabelText   $csharpLabel

在這裡,屬性模式用於處理字符串和字符集合,確保根據其屬性進行適當處理。

位置模式

在 C# 中,位置模式允許解構表達式結果並將結果值與對應的嵌套模式進行匹配。 PDF 的創建和生成由 iText 7 支持,而 HTML 到 PDF 的轉換由 pdfHTML 支持。

public readonly struct Point
{
    public int X { get; }
    public int Y { get; }
    public Point(int x, int y) => (X, Y) = (x, y);
    public void Deconstruct(out int x, out int y) => (x, y) = (X, Y);
}

static string Classify(Point point) => point switch
{
    (0, 0) => "Origin",
    (1, 0) => "Positive X basis end",
    (0, 1) => "Positive Y basis end",
    _ => "Just a point",
};
public readonly struct Point
{
    public int X { get; }
    public int Y { get; }
    public Point(int x, int y) => (X, Y) = (x, y);
    public void Deconstruct(out int x, out int y) => (x, y) = (X, Y);
}

static string Classify(Point point) => point switch
{
    (0, 0) => "Origin",
    (1, 0) => "Positive X basis end",
    (0, 1) => "Positive Y basis end",
    _ => "Just a point",
};
'INSTANT VB WARNING: VB has no equivalent to the C# readonly struct:
'ORIGINAL LINE: public readonly struct Point
Public Structure Point
	Public ReadOnly Property X() As Integer
	Public ReadOnly Property Y() As Integer
	Public Sub New(ByVal x As Integer, ByVal y As Integer)
'INSTANT VB TODO TASK: VB has no equivalent to the C# deconstruction assignments:
		(X, Y) = (x, y)
	End Sub
	Public Sub Deconstruct(<System.Runtime.InteropServices.Out()> ByRef x As Integer, <System.Runtime.InteropServices.Out()> ByRef y As Integer)
'INSTANT VB TODO TASK: VB has no equivalent to the C# deconstruction assignments:
		(x, y) = (X, Y)
	End Sub
End Structure

'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'static string Classify(Point point) => point switch
'{
'	(0, 0) => "Origin",
'	(1, 0) => "Positive X basis end",
'	(0, 1) => "Positive Y basis end",
'	_ => "Just a point",
'};
$vbLabelText   $csharpLabel

此示例中,使用位置模式對點進行基於其坐標的分類。

此外,您可以在屬性模式中引用嵌套屬性或字段,這稱為 C# 10 中引入的擴展屬性模式:

static bool IsAnyEndOnXAxis(Segment segment) =>
    segment is { Start.Y: 0 } or { End.Y: 0 };
static bool IsAnyEndOnXAxis(Segment segment) =>
    segment is { Start.Y: 0 } or { End.Y: 0 };
Shared Function IsAnyEndOnXAxis(ByVal segment As Segment) As Boolean
'INSTANT VB TODO TASK: The following 'is' operator pattern is not converted by Instant VB:
	Return segment is { Start.Y: 0 } [or] { [End].Y: 0 }
End Function
$vbLabelText   $csharpLabel

此功能通過允許直接訪問嵌套屬性來增強屬性模式的靈活性。

這些模式提供了處理複雜數據結構和提升代碼可讀性和表達力的強大機制。

Var 模式

Var 模式允許您匹配任何類型。 這在迭代結果的布爾表達式中或需要在 switch 案例保護中進行多次檢查時特別實用。

這裡有個例子展示了在布爾表達式中使用 var 模式:

static bool IsAcceptable(int id, int absLimit) =>
    SimulateDataFetch(id) is var results 
    && results.Min() >= -absLimit 
    && results.Max() <= absLimit;

static int [] SimulateDataFetch(int id)
{
    var rand = new Random();
    return Enumerable
               .Range(start: 0, count: 5)
               .Select(s => rand.Next(minValue: -10, maxValue: 11))
               .ToArray();
}
static bool IsAcceptable(int id, int absLimit) =>
    SimulateDataFetch(id) is var results 
    && results.Min() >= -absLimit 
    && results.Max() <= absLimit;

static int [] SimulateDataFetch(int id)
{
    var rand = new Random();
    return Enumerable
               .Range(start: 0, count: 5)
               .Select(s => rand.Next(minValue: -10, maxValue: 11))
               .ToArray();
}
Shared Function IsAcceptable(ByVal id As Integer, ByVal absLimit As Integer) As Boolean
	Dim tempVar As Boolean = TypeOf SimulateDataFetch(id) Is var
	Dim results = If(tempVar, CType(SimulateDataFetch(id), var), Nothing)
	Return tempVar AndAlso results.Min() >= -absLimit AndAlso results.Max() <= absLimit
End Function

Shared Function SimulateDataFetch(ByVal id As Integer) As Integer()
	Dim rand = New Random()
	Return Enumerable.Range(start:= 0, count:= 5).Select(Function(s) rand.Next(minValue:= -10, maxValue:= 11)).ToArray()
End Function
$vbLabelText   $csharpLabel

在這個例子中,SimulateDataFetch 返回一個整數數組,而 is var 模式將結果捕獲在 results 變量中,允許根據其屬性進行後續計算。

此外,var 模式可以在 switch 表達式或語句中使用,以達到更簡潔和易讀的代碼。 這名範例展示了在 switch 案例保護中使用 var 模式:

public record Point(int X, int Y);

static Point Transform(Point point) => point switch
{
    var (x, y) when x < y => new Point(-x, y),
    var (x, y) when x > y => new Point(x, -y),
    var (x, y) => new Point(x, y),
};

static void TestTransform()
{
    Console.WriteLine(Transform(new Point(1, 2)));  // output: Point { X = -1, Y = 2 }
    Console.WriteLine(Transform(new Point(5, 2)));  // output: Point { X = 5, Y = -2 }
}
public record Point(int X, int Y);

static Point Transform(Point point) => point switch
{
    var (x, y) when x < y => new Point(-x, y),
    var (x, y) when x > y => new Point(x, -y),
    var (x, y) => new Point(x, y),
};

static void TestTransform()
{
    Console.WriteLine(Transform(new Point(1, 2)));  // output: Point { X = -1, Y = 2 }
    Console.WriteLine(Transform(new Point(5, 2)));  // output: Point { X = 5, Y = -2 }
}
'INSTANT VB TODO TASK: C# 'records' are not converted by Instant VB:
'public record Point(int X, int Y)

'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'static Point Transform(Point point) => point switch
'{
'	var (x, y) when x < y => new Point(-x, y),
'	var (x, y) when x > y => new Point(x, -y),
'	var (x, y) => new Point(x, y),
'};

Shared Sub TestTransform()
	Console.WriteLine(Transform(New Point(1, 2))) ' output: Point { X = -1, Y = 2 }
	Console.WriteLine(Transform(New Point(5, 2))) ' output: Point { X = 5, Y = -2 }
End Sub
$vbLabelText   $csharpLabel

在這個例子中,var 模式 (x, y) 捕獲點的座標,允許根據其值進行不同的轉換。

在 var 模式中,所宣告變量的類型是從被匹配的表達式的編譯時期類型推斷出來的。

var 模式為處理各種情形提供了一種方便的方法,尤其是不提前知道特定的表達式類型時,增強了代碼的清晰度和靈活性。

介紹 IronPDF 庫

IronPDF 文檔渲染 是由 Iron Software 提供的一個專注於 PDF 文檔生成的庫。 要開始,首先要從 NuGet Package manager 或從 Visual Studio Package Manager 安裝該庫。

# To install from the NuGet Package Manager Console
Install-Package IronPdf
# To install from the NuGet Package Manager Console
Install-Package IronPdf
SHELL

下圖展示了如何從 Visual Studio 安裝指南 安裝。

C# Pattern Matching Expressions (How It Works For Developers): 圖 1 - 使用 NuGet package manager 安裝 IronPDF

在下面的代碼中,我們將看到如何生成一個簡單的 PDF 文檔:

using IronPdf;

namespace IronPatterns
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("-----------Iron Software-------------");
            var renderer = new ChromePdfRenderer(); // var pattern
            var content = " <h1> Iron Software is Awesome </h1> Made with IronPDF!";

            // Declaration Pattern
            int? nullableX = 8;
            int y = 45;
            object boxedy = y;
            content += "<p>Declaration Pattern</p>";
            if (nullableX is int a && boxedy is int b)
            {
                Console.WriteLine(a + b); // output: 53
                content += $"<p>Output: {(a + b)}</p>";
            }

            // Relational patterns
            content += "<p>Relational patterns</p>";
            var season1 = GetCalendarSeason(new DateTime(2024, 2, 25));
            Console.WriteLine(season1);
            content += $"<p>2024, 2, 25: {season1}</p>";
            var season2 = GetCalendarSeason(new DateTime(2024, 5, 25));
            Console.WriteLine(season2);
            content += $"<p>2024, 5, 25: {season2}</p>";
            var season3 = GetCalendarSeason(new DateTime(2024, 7, 25));
            Console.WriteLine(season3);
            content += $"<p>2024, 7, 25: {season3}</p>";

            var pdf = renderer.RenderHtmlAsPdf(content);
            pdf.SaveAs("output.pdf"); // Saves our PdfDocument object as a PDF        
        }

        static string GetCalendarSeason(DateTime date) => date.Month switch
        {
            >= 3 and < 6 => "spring",
            >= 6 and < 9 => "summer",
            >= 9 and < 12 => "autumn",
            12 or (>= 1 and < 3) => "winter",
            _ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
        };
    }
}
using IronPdf;

namespace IronPatterns
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("-----------Iron Software-------------");
            var renderer = new ChromePdfRenderer(); // var pattern
            var content = " <h1> Iron Software is Awesome </h1> Made with IronPDF!";

            // Declaration Pattern
            int? nullableX = 8;
            int y = 45;
            object boxedy = y;
            content += "<p>Declaration Pattern</p>";
            if (nullableX is int a && boxedy is int b)
            {
                Console.WriteLine(a + b); // output: 53
                content += $"<p>Output: {(a + b)}</p>";
            }

            // Relational patterns
            content += "<p>Relational patterns</p>";
            var season1 = GetCalendarSeason(new DateTime(2024, 2, 25));
            Console.WriteLine(season1);
            content += $"<p>2024, 2, 25: {season1}</p>";
            var season2 = GetCalendarSeason(new DateTime(2024, 5, 25));
            Console.WriteLine(season2);
            content += $"<p>2024, 5, 25: {season2}</p>";
            var season3 = GetCalendarSeason(new DateTime(2024, 7, 25));
            Console.WriteLine(season3);
            content += $"<p>2024, 7, 25: {season3}</p>";

            var pdf = renderer.RenderHtmlAsPdf(content);
            pdf.SaveAs("output.pdf"); // Saves our PdfDocument object as a PDF        
        }

        static string GetCalendarSeason(DateTime date) => date.Month switch
        {
            >= 3 and < 6 => "spring",
            >= 6 and < 9 => "summer",
            >= 9 and < 12 => "autumn",
            12 or (>= 1 and < 3) => "winter",
            _ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
        };
    }
}
Imports IronPdf

Namespace IronPatterns
	Friend Class Program
		Shared Sub Main()
			Console.WriteLine("-----------Iron Software-------------")
			Dim renderer = New ChromePdfRenderer() ' var pattern
			Dim content = " <h1> Iron Software is Awesome </h1> Made with IronPDF!"

			' Declaration Pattern
			Dim nullableX? As Integer = 8
			Dim y As Integer = 45
			Dim boxedy As Object = y
			content &= "<p>Declaration Pattern</p>"
			Dim tempVar As Boolean = TypeOf boxedy Is Integer
			Dim b As Integer = If(tempVar, DirectCast(boxedy, Integer), Nothing)
			Dim tempVar2 As Boolean = TypeOf nullableX Is Integer
			Dim a As Integer = If(tempVar2, CInt(nullableX), Nothing)
			If tempVar2 AndAlso tempVar Then
				Console.WriteLine(a + b) ' output: 53
				content &= $"<p>Output: {(a + b)}</p>"
			End If

			' Relational patterns
			content &= "<p>Relational patterns</p>"
			Dim season1 = GetCalendarSeason(New DateTime(2024, 2, 25))
			Console.WriteLine(season1)
			content &= $"<p>2024, 2, 25: {season1}</p>"
			Dim season2 = GetCalendarSeason(New DateTime(2024, 5, 25))
			Console.WriteLine(season2)
			content &= $"<p>2024, 5, 25: {season2}</p>"
			Dim season3 = GetCalendarSeason(New DateTime(2024, 7, 25))
			Console.WriteLine(season3)
			content &= $"<p>2024, 7, 25: {season3}</p>"

			Dim pdf = renderer.RenderHtmlAsPdf(content)
			pdf.SaveAs("output.pdf") ' Saves our PdfDocument object as a PDF
		End Sub

'INSTANT VB TODO TASK: The following 'switch expression' was not converted by Instant VB:
'		static string GetCalendarSeason(DateTime date) => date.Month switch
'		{
'			>= 3 and < 6 => "spring",
'			>= 6 and < 9 => "summer",
'			>= 9 and < 12 => "autumn",
'			12 or (>= 1 and < 3) => "winter",
'			_ => throw new ArgumentOutOfRangeException(nameof(date), $"Date with unexpected month: {date.Month}."),
'		};
	End Class
End Namespace
$vbLabelText   $csharpLabel

輸出

C# Pattern Matching Expressions (How It Works For Developers): 圖 2

代碼詳情

在此我們使用 IronPDF 的 ChromePdfRenderer將 HTML 字符串保存到 PDF 文檔中。 輸出保存到「output.pdf」文檔中。

試用授權

IronPDF can be used with a trial license obtained from the IronPDF Licensing Page. 提供 Email Id 生成將發送到您郵箱的授權密鑰。

"IronPDF.LicenseKey": "<Your Key>"
"IronPDF.LicenseKey": "<Your Key>"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPDF.LicenseKey": "<Your Key>"
$vbLabelText   $csharpLabel

將授權密鑰放置在 appsettings.json 文件中如上所示。

結論

C# 中的模式匹配表達式提供了一種有力而靈活的書寫條件語句、類型檢查和對象解構的方式,簡潔且可讀。 通過利用模式匹配,開發者可以提高代碼的清晰性和可維護性,同時減少樣板和冗餘。 無論是類型檢查、switch 語句,還是解構,模式匹配表達式都提供了應對 C# 中廣泛程式設計任務的一種通用工具集。

總的來說,掌握模式匹配表達式能極大提高您的 C# 編程技巧,使您能夠寫出更乾淨、更具表現力、易理解和維護的代碼。 我們還涵蓋了IronPDF 的 HTML 到 PDF 生成能力,這可以用於生成 PDF 文檔。

常見問題解答

我如何使用模式匹配來提高 C# 中代碼的可讀性?

C# 中的模式匹配允許開發人員編寫更簡潔和富於表達的代碼,使條件語句更清晰且易於理解。這通過減少代碼塊的複雜性來提高了可讀性和可維護性。

C# 中提供哪些不同類型的模式匹配表達式?

C# 支持多種模式匹配表達式,包括 is 表達式,switch 語句和 switch 表達式。每種類型都提供了不同的方式來評估表達式並根據匹配模式執行代碼。

我如何使用 C# 生成 PDF 文檔?

您可以使用 IronPDF,這是來自 Iron Software 的庫,用於在 C# 中生成 PDF 文檔。它允許將 HTML 內容轉換成 PDF,並可通過 NuGet 輕鬆安裝,提供了豐富的 PDF 生成功能。

什麼是 C# 模式匹配中的聲明和類型模式?

C# 中的聲明和類型模式檢查一個表達式的運行時類型是否與一個指定的類型匹配,並允許在匹配成功時聲明一個新的局部變量,以促進類型安全的操作。

C# 中的常量模式如何運行?

C# 中的常量模式用於檢查一個表達式是否等於一個特定的常量值,如整數或字符串,並在找到匹配時執行某些邏輯,從而實現簡單的常量值比較。

C# 中的關係模式的用途是什麼?

C# 中的關係模式允許使用關係運算符如 <><=>= 將表達式與常量進行比較。這對於在代碼中實現簡潔的範圍檢查很有用。

如何在 C# 中應用邏輯模式?

C# 中的邏輯模式使用邏輯運算符如 andornot 組合其他模式,允許為復雜的模式匹配條件設置,可同時評估多個標準。

C# 中的丟棄模式是什麼,何時使用?

C# 中的丟棄模式,由 _ 表示,匹配任何表達式,包括 null,通常用於需要忽略特定值的情況,例如在 switch 表達式中使用。

如何在 C# 中利用屬性模式?

C# 中的屬性模式允許開發人員將一個對象的屬性或字段與嵌套模式進行匹配,提供了一種在維持清晰簡潔代碼的同時進行對象結構深層檢查的方法。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。