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 }