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#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20107 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
追逐时光者19 小时前
.NET Fiddle:一个方便易用的在线.NET代码编辑工具
后端·.net
mudtools21 小时前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
追逐时光者1 天前
精选 4 款基于 .NET 开源、功能强大的 Windows 系统优化工具
后端·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫2 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
私人珍藏库2 天前
[Windows] 微软 .Net 运行库离线安装包 | Microsoft .Net Packages AIO_v09.09.25
microsoft·.net·运行库