使用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 }
复制代码

 

posted @   data_byte  阅读(173)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示