Skip to content

ZH TW CSharp Patterns

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

模式匹配

手冊C# · 範例UO

模板同時檢查值並可以檢索資料。提供常數、類型、屬性、位置、關係、列表和邏輯組合 and、or、not 的模板。 _表示丟棄值。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
int value = 15;
System.Console.WriteLine(value is > 10 and < 20);

結果:

True
object value = "backpack";
if (value is string { Length: > 0 } name)
{
    UO.Print(name);
}
int[] numbers = [1, 2, 3];
string shape = numbers switch
{
    [1, .., 3] => "starts with 1 and ends with 3",
    [] => "empty",
    _ => "other"
};
UO.Print(shape);

官方文件:模式匹配 - Microsoft Learn。

Clone this wiki locally