類型模式
類型模式可啟用簡潔類型計算和轉(zhuǎn)換。 使用 switch 語句執(zhí)行模式匹配時,會測試表達式是否可轉(zhuǎn)換為指定類型,如果可以,則將其轉(zhuǎn)換為該類型的一個變量。 語法為:
C#復(fù)制
case type varname
其中 type 是 expr 結(jié)果要轉(zhuǎn)換到的類型的名稱,varname 是 expr 結(jié)果要轉(zhuǎn)換到的對象(如果匹配成功)。 自 C# 7.1 起,expr 的編譯時類型可能為泛型類型參數(shù)。
如果以下任一條件成立,則 case 表達式為 true:
expr 是與 type 具有相同類型的一個實例。
expr 是派生自 type 的類型的一個實例。 換言之,expr 結(jié)果可以向上轉(zhuǎn)換為 type 的一個實例。
expr 具有屬于 type 的一個基類的編譯時類型,expr 還具有屬于 type 或派生自 type 的運行時類型。 變量的編譯時類型 是其類型聲明中定義的變量類型。 變量的運行時類型 是分配給該變量的實例類型。
expr 是實現(xiàn) type 接口的類型的一個實例。
如果 case 表達式為 true,將會明確分配 varname,并且僅在開關(guān)部分中具有本地作用域。
請注意,null 與任何類型都不匹配。 若要匹配 null,請使用以下 case 標(biāo)簽:
C#復(fù)制
case null:
以下示例使用類型模式來提供有關(guān)各種集合類型的信息。
C#復(fù)制
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Example
{
static void Main(string[] args)
{
int[] values = { 2, 4, 6, 8, 10 };
ShowCollectionInformation(values);
var names = new List<string>();
names.AddRange( new string[] { "Adam", "Abigail", "Bertrand", "Bridgette" } );
ShowCollectionInformation(names);
List<int> numbers = null;
ShowCollectionInformation(numbers);
}
private static void ShowCollectionInformation(object coll)
{
switch (coll)
{
case Array arr:
Console.WriteLine($"An array with {arr.Length} elements.");
break;
case IEnumerable<int> ieInt:
Console.WriteLine($"Average: {ieInt.Average(s => s)}");
break;
case IList list:
Console.WriteLine($"{list.Count} items");
break;
case IEnumerable ie:
string result = "";
foreach (var e in ie)
result += "${e} ";
Console.WriteLine(result);
break;
case null:
// Do nothing for a null.
break;
default:
Console.WriteLine($"A instance of type {coll.GetType().Name}");
break;
}
}
}
// The example displays the following output:
// An array with 5 elements.
// 4 items