在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; }
}
}