switch 类型模式

2019-10-09  本文已影响0人  落地成佛

类型模式

类型模式可启用简洁类型计算和转换。 使用 switch 语句执行模式匹配时,会测试表达式是否可转换为指定类型,如果可以,则将其转换为该类型的一个变量。 语法为:

C#复制

   case type varname

其中 typeexpr 结果要转换到的类型的名称,varnameexpr 结果要转换到的对象(如果匹配成功)。 自 C# 7.1 起,expr 的编译时类型可能为泛型类型参数。

如果以下任一条件成立,则 case 表达式为 true

如果 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
上一篇 下一篇

猜你喜欢

热点阅读