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

相关推荐
第二层皮-合肥1 天前
基于C#的工业测试控制软件-总体框架
开发语言·c#
steins_甲乙1 天前
C# 通过共享内存与 C++ 宿主协同捕获软件窗口
开发语言·c++·c#·内存共享
毕设源码-邱学长1 天前
【开题答辩全过程】以 基于.net mvc剧本杀预约与管理为例,包含答辩的问题和答案
mvc·.net
似水明俊德1 天前
12-C#.Net-加密解密-学习笔记
笔记·学习·oracle·c#·.net
阿蒙Amon1 天前
C#常用类库-详解SSH.NET
c#·ssh·.net
似水明俊德1 天前
11-C#.Net-多线程-Async-Await篇-学习笔记
开发语言·笔记·学习·c#·.net
美团骑手阿豪1 天前
C#语法:HashSet与List对比,适合场景
unity·c#
wr1 天前
Modbus 读写转换
c#
公子小六1 天前
基于.NET的Windows窗体编程之WinForms入门简介
windows·microsoft·c#·.net