使用switch表达式简化switch语句
1 using System; 2 using System.IO; 3 4 public class Program 5 { 6 public static void Main() 7 { 8 string path = @"C:\Users\user\Downloads"; 9 Console.Write("Press R for readonly or W for write:"); 10 ConsoleKeyInfo key = Console.ReadKey(); 11 Console.WriteLine(); 12 13 Stream s = null; 14 if(key.Key == ConsoleKey.R) 15 { 16 s = File.Open( 17 Path.Combine(path,"file.txt"), 18 FileMode.OpenOrCreate, 19 FileAccess.Read); 20 } 21 else 22 { 23 s = File.Open( 24 Path.Combine(path,"file.txt"), 25 FileMode.OpenOrCreate, 26 FileAccess.Write); 27 } 28 29 //以往写法 30 string message = string.Empty; 31 switch(s) 32 { 33 case FileStream writeableFile when s.CanWrite: 34 message = "The stream is a file that I can write to."; 35 break; 36 case FileStream readOnlyFile: 37 message = "The stream is a read-only file."; 38 break; 39 case MemoryStream ms: 40 message = "The stream is a memory address."; 41 break; 42 default: 43 message = "The stream is some other type."; 44 break; 45 case null: 46 message = "The stream is null"; 47 break; 48 } 49 50 //C#8.0以上switch表达式简化switch语句 51 message = s switch 52 { 53 FileStream writeableFile when s.CanWrite 54 =>"The stream is a file that I can write to.", 55 FileStream readOnlyFile 56 =>"The stream is a read-only file.", 57 MemoryStream ms 58 =>"The stream is a memory address.", 59 null 60 =>"The stream is null", 61 _ 62 =>"The stream is some other type." 63 }; 64 Console.WriteLine(message); 65 66 } 67 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗