zoukankan      html  css  js  c++  java
  • 使用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 }
  • 相关阅读:
    android数据恢复
    UVA 690 Pipeline Scheduling
    2017 国庆湖南 Day4
    2017 国庆湖南 Day5
    2017 国庆湖南 Day6
    2017国庆 清北学堂 北京综合强化班 Day1
    2017 国庆湖南Day2
    bzoj 2962 序列操作
    UVA 818 Cutting Chains
    UVA 211 The Domino Effect
  • 原文地址:https://www.cnblogs.com/yushihua/p/15787884.html
Copyright © 2011-2022 走看看