新的匹配功能

本文关键字:功能 | 更新日期: 2023-09-27 18:05:27

我下载了Enterprise 2015 Preview 3。我如何使这个程序在c# 7下工作?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
abstract class Animal { }
class Dog : Animal
{
    public string BarkLikeCrazy()
    {
        return "WOOF WOOF WOOF";
    }
}
class Cat : Animal { }
class Swan : Animal { }
class Program
{
    static void Main(string[] args)
    {
        var animals = new Animal[] { new Dog(), new Cat(), new Swan() };
        var organizedAnimals = from animal in animals
                               let sound = animal match(
                                    case Dog d: "woof... " + d.BarkLikeCrazy()
                                    case Cat c: "meow"
                                    case * : "I'm mute.."
                              )
                              select new { Type = animal, Sound = sound };
        foreach (var animal in organizedAnimals)
        {
            Console.WriteLine($"{animal.Type.ToString()} - {animal.Sound}");
        }
        Console.ReadKey();
    }
}

新的匹配功能

match关键字更改为switch

var organizedAnimals = from animal in animals
                       let sound = animal switch(
                            case Dog d: "woof... " + d.BarkLikeCrazy()
                            case Cat c: "meow"
                            case * : "I'm mute.."
                      )
                      select new { Type = animal, Sound = sound };

你可以在GitHub上的讨论中了解它的演变(在被合并到模式匹配规范之前)。

下面是GitHub特性讨论中的一个示例:

var areas =
    from primitive in primitives
    let area = primitive switch (
        case Line l: 0,
        case Rectangle r: r.Width * r.Height,
        case Circle c: Math.PI * c.Radius * c.Radius,
        case *: throw new ApplicationException()
    )
    select new { Primitive = primitive, Area = area };

如何使这个程序在c# 7下工作?

你不。基于表达式的模式匹配在当前的c# 7.0预览版中是不可用的,也不会在c# 7.0的最终版本中出现。

目前计划在"c# 7.0 + 1"中的表单是这样的:

var organizedAnimals = from animal in animals
                       let sound = animal switch (
                            case Dog d: "woof... " + d.BarkLikeCrazy(),
                            case Cat c: "meow",
                            case *: "I'm mute.."
                        )
                        select new { Type = animal, Sound = sound };