一些算法依赖于多个输入。 使用元组模式,可根据表示为​​元组​​的多个值进行切换 。

注意在使用switch时,switch里面用的是小括号(),属性模式用的是大括号{}。

以下根据星期和天气判断今天状态如何:

using System;
using System.Collections.Generic;
using System.Text;

namespace BasicKnowledgeTest
{
public class Week
{
public Weekday Name { get; set; }
public string Weather { get; set; }

}

public static class TestTubeMode
{
// 根据星期和天气判断今天状态如何
public static string GetStatusByWeekday(Week day) =>
(day.Name, day.Weather) switch
{
(Weekday.Sun,"Sunny")=> "today is good",
(Weekday.Sat, "Sunny")=> "today is very good",
(Weekday.Mon, "Sunny")=> "today is not good",
(Weekday.Sun, "Rainy")=> "today is not good",
_ => throw new ArgumentException(message: "invalid enum value"),
};
}
}

测试

using System;
using System.Diagnostics;

namespace BasicKnowledgeTest
{
class Program
{
static void Main(string[] args)
{
var result = TestTubeMode.GetStatusByWeekday(new Week(){Name=Weekday.Sun, Weather= "Sunny" });
Console.WriteLine(result);
Console.ReadLine();
}
}
}

测试结果


C# 8.0 新增功能 —模式匹配增强功能—元组模式_公众号




C# 8.0 新增功能 —模式匹配增强功能—元组模式_公众号_02 公众号_DotNet微说.jpg