跳過到頁腳內容
.NET幫助

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

C#中的模式匹配是一個強大的功能,首次出現在C# 7.0並在隨後的版本中得到擴展。 它允許開發者在處理條件語句、類型檢查和對象解構時編寫更簡潔和具表達力的代碼。

模式匹配表達式提供了一種靈活且直觀的方式來將值與模式匹配並執行相應的代碼塊。 在本文中,我們將探討C#中模式匹配表達式的複雜性,包括語法、用例和代碼示例。 文章結束時,我們還將探討Iron SoftwareIronPDF PDF Generation Library,用以在C#應用程式中動態生成PDF文件。

Benefits of Pattern Matching in C#

C#代碼中的模式匹配具有諸多優勢:

  • 增強的可讀性:模式匹配簡化了複雜的條件邏輯,使您的代碼對您自己和其他開發者而言更易於理解和跟隨。
  • 代碼行數減少:通過將複雜的條件語句濃縮為簡潔的模式,模式匹配有助於精簡您的代碼庫,從而減少代碼行數並提供更簡潔的實現。
  • 提高了可維護性:模式匹配提供的清晰度促進了更容易的代碼維護和除錯。 隨著模式的清晰劃分,可以更輕鬆地按需識別和修改特定的邏輯塊,而不影響其餘的代碼庫。
  • 更具表達力的算法:模式匹配賦予開發者以更自然和直觀的方式來表達算法。 通過使代碼結構與問題解決範式對齊,模式匹配便利了與其概念模型密切類似的算法創建。

Types of Pattern Matching in C#

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

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

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

聲明和類型模式

聲明和類型模式是C#中檢查表達式運行時類型與給定類型兼容性的必備工具。使用聲明模式,您可以同時檢查兼容性並聲明新的本地變量。 請考慮以下範例:

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!
}
$vbLabelText   $csharpLabel

在此,聲明模式確保如果表達式message,允許後續操作。

當下列任意條件成立時,聲明模式有效:

  • 表達式的運行時類型為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
}
$vbLabelText   $csharpLabel

在此,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)),
};
$vbLabelText   $csharpLabel

在此代碼段中,_充當與任一類型匹配的佔位符。

聲明和類型模式都確保表達式在模式匹配前非空。 您可以使用否定空常量模式來檢查非空,如以下示例所示:

if (inputVal is not null)
{
    // ...
}
if (inputVal is not null)
{
    // ...
}
$vbLabelText   $csharpLabel

此否定確保inputVal非空才進行進一步操作。

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

常量模式

常量模式用以驗證表達式結果是否匹配特定的常數值。 請考慮以下範例:

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)),
};
$vbLabelText   $csharpLabel

在此,常量模式檢查visitorCount是否匹配任一指定的常數值並返回相應的票價。

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

  1. 整數或浮點數數值字面量。
  2. 字元。
  3. 字串字面量。
  4. 布林值(false)。
  5. 列舉值。
  6. 已聲明的const字段或本地的名稱。
  7. null.

類型ReadOnlySpan<char>的表達式可匹配固定字符串。

要檢查null,請像這樣利用常量模式:

if (inputVal is null)
{
    return;
}
if (inputVal is null)
{
    return;
}
$vbLabelText   $csharpLabel

在此,模式確保inputVal為空才進行進一步操作。

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

if (inputVal is not null)
{
    // ...
}
if (inputVal is not null)
{
    // ...
}
$vbLabelText   $csharpLabel

此模式驗證inputVal非空,允許安全的後續操作。

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

關係模式

關係模式提供了與常數比較表達式結果的方法。 請考慮以下範例:

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",
};
$vbLabelText   $csharpLabel

在此,關係模式將measurement與特定閾值進行比較,以確定其分類。

關係模式的右側必須為一個常量表達式,可以是整數、浮點數、enum類型。 左側可以使用>=運算符。

要匹配在某個範圍內的表達式結果,請使用連詞"和"模式,如下所示:

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}."),
};
$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,
};
$vbLabelText   $csharpLabel

在上面的丟棄模式示例中,處理了所有可能的輸入值。 一周的所有日子都管理並提供了一個默認值。 如此一來,所有可能的值都得以處理。 丟棄模式不能在switch語句中用作模式。 在此類情況下,可以使用帶丟棄的var _,來匹配任何表達式。 然而,丟棄模式在switch表達式中是允許的。 欲知詳情,請參考功能提案說明的棄用模式部分。

邏輯模式

C#中的邏輯模式提供了強大的模式匹配工具,包括否定、合取和析取,這樣可以有更靈活和表達力的匹配條件。

否定(not模式)

否定模式,由not表示,當否定的模式不匹配表達式時匹配一個表達式。 這特別適用於檢查表達式是否非空,如下面所示:

if (input is not null)
{
    // ...
}
if (input is not null)
{
    // ...
}
$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",
};
$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}."),
};
$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 };
$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."),
};
$vbLabelText   $csharpLabel

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

位置模式

在C#中,位置模式允許對表達式結果進行解構,並將結果值與相應的嵌套模式進行匹配。 例如:

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",
};
$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 };
$vbLabelText   $csharpLabel

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

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

Var模式

Var模式允許匹配任一類型。 這對於在布林表達式中捕獲中間結果或在switch case保護中需要多次檢查的情況下特別有用。

這裡有一個示例,說明了在布林表達式中使用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();
}
$vbLabelText   $csharpLabel

在此示例中,results中,允許在其屬性基礎上進行後續計算。

此外,var模式可以在switch表達式或語句中使用,以獲得更簡潔和可讀的代碼。 這裡有一個使用var模式在switch case保護中使用的示例:

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 }
}
$vbLabelText   $csharpLabel

在此示例中,var模式(x, y)捕獲點的坐標,允許基於其值進行不同的轉換。

在var模式中,所聲明變量的類型是從與模式匹配的表達式的編譯時類型中推斷出來的。

var模式提供了一種方便的方法來處理在事先不知道的各種情況下的表達式特定類型,改善代碼的清晰度和靈活性。

介紹IronPDF Library

IronPDF Document Rendering是Iron Software的一個資料庫,專門用於生成PDF文件。 要開始使用,首先需要從NuGet包管理器或Visual Studio包管理器安裝該庫。

# 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#模式匹配表達式(對開發者的運作方式):圖1 – 使用NuGet包管理器安裝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}."),
        };
    }
}
$vbLabelText   $csharpLabel

輸出

C#模式匹配表達式(對開發者的運作方式):圖2

代碼詳情

這裡我們使用IronPDF的ChromePdfRenderer將HTML字符串保存為PDF文件。 輸出保存到"output.pdf"文件。

試用授權

IronPDF可以使用從IronPDF Licensing Page取得的試用授權。 提供一個電子郵件ID以生成授權金鑰,將通過電子郵件發送至您的郵箱。

"IronPdf.LicenseKey": "<Your Key>"
"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# 中的屬性模式允許開發人員將一個對象的屬性或字段與嵌套模式進行匹配,提供了一種在維持清晰簡潔代碼的同時進行對象結構深層檢查的方法。

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技術的創新,同時指導下一代技術領導者。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me