C#的switch和模式匹配

在C#的switch雨季中不能删除不同case的break来实现fall through,不过对于常量模式的case语句,可以使用goto语句实现。对于类型模式和关系模式,暂时还没有成。

using System;
using static System.Console;

class Program
{
    static void Main()
    {
        WriteLine("hello world");
        int temp = 0;
        temp = Convert.ToInt32(ReadLine());
        object o = temp;
        switch(o)
        {
            case null:
                WriteLine("const pattern with null");
                break;
            case int y when y > 32:
                WriteLine("Type pattern with condition");
                //C#的switch是不允许省略break来实现贯穿的 即fall through
                //对于常量模式 可以用goto语句实现贯穿,对于其他模式好像不太行
                goto case "hello";
                break;
            //x 这里说在C#9以上才能使用类型模式 所以这里加了一个x才能编译通过
            case int x:
                WriteLine("Type pattern without condition");
                break;
                break;
                //这里也一样 在当前7.3里不让省略b C#9里应该可以
            case Book b:
                WriteLine(b.Author);
                break;
            case "hello":
                WriteLine("this is an exact num");
                break;
             default:
                WriteLine("hel");
                break;

        }
    }
    internal class Book
    {
        public Book(String title) => Title = title;
        public String Title { get; set; }
        public String Author { get; set; }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值