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

相关推荐
专注VB编程开发20年1 小时前
WebView2 处理跨域访问限制,Frame脚本执行,难度比CEF大10倍
前端·javascript·.net
github.com/starRTC3 小时前
Claude Code中英文系列教程34:再谈Skills
开发语言·c#·ai编程
bugcome_com5 小时前
C# 判断语句详解(if、switch、三目运算符、Null 条件运算符)
c#
霸王•吕布7 小时前
C#-使用OpenTK渲染3D模型
c#·opentk·glcontrol
游乐码7 小时前
c#封装成员变量和成员方法和访问修饰符
开发语言·c#
Never_Satisfied8 小时前
在c#中,Jint的AsString()和ToString()的区别
服务器·开发语言·c#
Never_Satisfied8 小时前
在c#中,获取文件的大小
java·开发语言·c#
weixin_468466858 小时前
PyTorch导出ONNX格式分割模型及在C#中调用预测
人工智能·pytorch·深度学习·c#·跨平台·onnx·语义分割
光泽雨17 小时前
C# 中 Assembly 类详解
开发语言·c#
少控科技17 小时前
C#基础训练营 - 02 - 运算器
开发语言·c#