C# .Net8 switch 的用法

在 .net 8中,switch 不需要再和传统的写法一样了,会更加的方便

创建一个 .net 8 控制台项目

switch 的写法没必要和以前一样

cs 复制代码
namespace SwitchTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int day = 3;

            var week = day switch
            {
                1 => "Monday",
                2 => "Tuesday",
                3 => "Wednesday",
                4 => "Thursday",
                5 => "Friday",
                _ => "oh shit"
            } ;

            Console.WriteLine(week);
        }
    }
}

运行:

如果将 day 设置为 30,在所有的选择中都找不到,那么结果就自动执行 _ 选项代码

cs 复制代码
namespace SwitchTest
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int day = 30;

            var week = day switch
            {
                1 => "Monday",
                2 => "Tuesday",
                3 => "Wednesday",
                4 => "Thursday",
                5 => "Friday",
                _ => "oh shit"
            } ;

            Console.WriteLine(week);
        }
    }
}

运行:

遍历枚举写法一样

cs 复制代码
namespace SwitchTest
{
    internal class Program
    {
        enum color { red, yellow, green }

        static void Main(string[] args)
        {
            color myColos = color.red;
            string colosStr = myColos switch
            {
                color.red => "红",
                color.yellow => "黄",
                color.green => "绿",
                _ => throw new Exception()
            } ;
            Console.WriteLine(colosStr);
        }
    }
}

end

相关推荐
czhc11400756639 小时前
C# 428 线程、异步
开发语言·c#
唐青枫10 小时前
C#.NET ThreadLocal 深入解析:线程独享数据、性能收益与实战边界
c#·.net
烟话617 小时前
实际内存条,虚拟内存,堆,栈
c#
归途醉染17 小时前
Swifter.Json
c#·json·swifter.json
伽蓝_游戏18 小时前
第一章:解构游戏资源
游戏·unity·性能优化·c#·游戏引擎·游戏程序·assetbundle
SEO-狼术18 小时前
Include Scannable Barcodes in Reports
.net
星辰徐哥19 小时前
Unity C#入门:Visual Studio与Unity的关联配置
unity·c#·visual studio
星辰_mya20 小时前
分布式系统里的“快递中转站”——消息队列(MQ)
c#·linq
qq_4312807021 小时前
工作经验总结:半导体上位机软件开发与互联网开发的不同
c#·.net
Metaphor69221 小时前
使用 Python 查找并替换 Word 文档中的文本
python·c#·word