gpt4 book ai didi

c# - 新匹配功能

转载 作者:行者123 更新时间:2023-11-30 17:36:32 25 4
gpt4 key购买 nike

我下载了 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 };

您可以在 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 };

关于c# - 新匹配功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39279548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com