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

相关推荐
周杰伦fans12 小时前
C# required 关键字详解
开发语言·网络·c#
游乐码14 小时前
c#ArrayList
开发语言·c#
唐青枫14 小时前
C#.NET Monitor 与 Mutex 深入解析:进程内同步、跨进程互斥与使用边界
c#·.net
周杰伦fans15 小时前
cad文件选项卡不见了怎么办?
c#
llm大模型算法工程师weng16 小时前
Python敏感词检测方案详解
开发语言·python·c#
会写代码的建筑师16 小时前
.NET 控制台后台程序实践细节总结
后端·.net
游乐码16 小时前
c#stack
开发语言·c#
橘子编程16 小时前
编程语言全指南:从C到Rust
java·c语言·开发语言·c++·python·rust·c#
阿捞216 小时前
在 .NET 中使用 Moonshot Kimi + AgentFramework:从 SDK 到 Agent 的完整实践
html·.net·xhtml
zztfj17 小时前
C# 异步方法 async / await CancellationToken 设置任务超时并手动取消耗时处理
c#·异步