我下载了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();
}
}
答案 0 :(得分:1)
将您的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 };
您可以在discussion on GitHub(在合并到模式匹配规范之前)中了解此演变。
以下是来自GitHub feature discussion:
的示例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 };
答案 1 :(得分:0)
如何使该程序在C#7下工作?
你没有。基于表达式的模式匹配在C#7.0的当前预览中不可用,并且不计划用于C#7.0的最终版本。
The form that's currently planned for "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 };