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

相关推荐
清风与日月15 小时前
c# 集成激光雷达(以思岚A1为例)
开发语言·c#
无极小卒15 小时前
如何在三维空间中生成任意方向的矩形内部点位坐标
开发语言·算法·c#
the白勺17 小时前
RabbitMQ-基础-总结
开发语言·c#
专注VB编程开发20年18 小时前
C#VB.NET中实现可靠的文件监控(新建、删除、改名、内容修改等事件的准确捕获)
spring·c#·.net·文件监控
yi碗汤园20 小时前
【一文了解】C#反射
开发语言·unity·c#
T.Ree.1 天前
汇编_读写内存
开发语言·汇编·c#
czhc11400756631 天前
C#1114 枚举
开发语言·c#
曹牧1 天前
C#中,GetValueOrDefault方法
c#
胡八一1 天前
Windows 7 运行 .NET 应用时报错“hostfxr.dll 加载失败 (HRESULT: 0x80070057)”的彻底解决指南
windows·.net
勿芮介1 天前
[大模型应用].Net下接入VLM多模态模型分析
.net·ai编程