类型模式
类型模式可启用简洁类型计算和转换。 使用 switch
语句执行模式匹配时,会测试表达式是否可转换为指定类型,如果可以,则将其转换为该类型的一个变量。 语法为:
C#复制
case type varname
其中 type 是 expr 结果要转换到的类型的名称,varname 是 expr 结果要转换到的对象(如果匹配成功)。 自 C# 7.1 起,expr 的编译时类型可能为泛型类型参数。
如果以下任一条件成立,则 case
表达式为 true
:
-
expr 是与 type 具有相同类型的一个实例。
-
expr 是派生自 type 的类型的一个实例。 换言之,expr 结果可以向上转换为 type 的一个实例。
-
expr 具有属于 type 的一个基类的编译时类型,expr 还具有属于 type 或派生自 type 的运行时类型。 变量的编译时类型 是其类型声明中定义的变量类型。 变量的运行时类型 是分配给该变量的实例类型。
-
expr 是实现 type 接口的类型的一个实例。
如果 case 表达式为 true,将会明确分配 varname,并且仅在开关部分中具有本地作用域。
请注意,null
与任何类型都不匹配。 若要匹配 null
,请使用以下 case
标签:
C#复制
case null:
以下示例使用类型模式来提供有关各种集合类型的信息。
C#复制
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
网友评论