2016-12-04 54 views
1

我正在使用下面的代碼根據使用switch語句的用戶輸入類型執行轉換。是否可以在這裏使用「enum」和「struct」而不是switch語句?枚舉和結構代替C語言中的switch語句的用法

using System; 
using static System.Console; 
using static System.Convert; 

namespace Problem 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      double centimeter, liters, kilometer, kilogram; 
      WriteLine("Enter the value you wanted to convert: "); 
      int input = ToInt32(ReadLine()); 
      WriteLine("\n Press Any Of The Given Choices \n I->convert from inches to centimeters." + 
         "\n G->convert from gallons to liters.\n M->convert from mile to kilometer."+ 
         "\n P->convert from pound to kilogram."); 
      char choice = Char.ToLower(ToChar(ReadLine())); 
      switch (choice) 
      { 
       case 'i': 
        centimeter = input/0.3937;      //1 cm is equal is 0.3037 inch 
        WriteLine($"In Centimeters: {centimeter}"); 
        break; 
       case 'g': 
        liters= input * 3.78;        // 1 gallon=3.78 litters 
        WriteLine($"In Liters: { liters}"); 
        break; 
       case 'm': 
        kilometer = input *1.60;       // 1 mile=1.4 KM 
        WriteLine($"In kilometer: { kilometer}"); 
        break; 
       case 'p': 
        kilogram = input * 0.453;       // 
        WriteLine($"In kilogram: { kilogram}"); 
        break; 
       default: 
        WriteLine("You Enter A Invalid Choice, Please Enter A Valid Choice...!"); 
        ReadLine(); 
        break; 
        } 
      ReadKey(); 
     } 
    } 
} 

回答

2

您可以使用Dictionary代替switch聲明。
對於您可以創建界面

public interface IConverter 
{ 
    string GetFormattedResult(int value); 
} 

然後創建爲每個單位自己的實現必須

public class CentimeterConverter : IConverter 
{ 
    private const double COEFFICENT = 0.3937; 
    public string GetFormattedResult(int value) 
    { 
     var centimeter = input/COEFFICENT ; 
     return $"In Centimeters: {centimeter}"; 
    } 
} 
在你的代碼

然後創建字典與重點更清潔的方式 - 選擇焦炭和價值 - 轉換器的實例實施

static void Main(string[] args) 
{ 
    var converters = new Dictionary<char, IConverter> 
    { 
     { 'i', new CentimeterConverter() }, 
     { 'g', new LitersConverter() } 
    } 

    WriteLine("Enter the value you wanted to convert: "); 
    int input = ToInt32(ReadLine()); 

    var choiceText = 
     "Press Any Of The Given Choices 
     I->convert from inches to centimeters. 
     G->convert from gallons to liters. 
     M->convert from mile to kilometer. 
     P->convert from pound to kilogram."; 
    WriteLine(choiceText); 

    char choice = Char.ToLower(ToChar(ReadLine())); 

    var converter = converters[choice]; 
    WriteLine(converter.Convert(input)); 

    ReadKey(); 
} 

爲了使鍵很少出價更具可讀性,您可以使用靜態類與常量

public static class ConverterKayes 
{ 
    public const char InchesToCentimaters = 'i'; 
    public const char GallonsToLiters = 'g'; 
} 

枚舉是整數類型,這樣你就可以創建枚舉,這裏的名字將鑰匙

public enum Keys 
{ 
    I = 1, 
    G = 2 
} 

但這枚舉沒有給出更多的價值,你的代碼的可讀性。

如果你真的想枚舉,那麼你可以使用DescriptionAttribute在那裏你可以在屬性

public enum Keys 
{ 
    [Description("I")] InchesToCentimeters = 1, 
    [Description("G")] GallonsToLiters = 2 
} 

定義鍵但您需要創建一些方法來從屬性檢索值。 同系數 - 它很容易保存爲靜態類的常量。

另一種方法可以KeyedCollection,也可以是適合你的情況,因爲你必須爲所有的密鑰相同的邏輯,只值改變

public class ConverterToContinentalUnit 
{ 
    public char Key { get; set; } 
    public double Coefficent { get; set; } 
    public string PrefixForResult { get; set; } 

    public string GetFormattedResult(int value) 
    { 
     var continentalUnit = input/Coefficent; 
     return $"{PrefixForResult}: {continentalUnit}"; 
    } 
} 

public class ConverterCollection: KeyedCollection<int, ConverterToContinentalUnit> 
{ 
    // This need to be implemented and return key value 
    protected override int GetKeyForItem(ConverterToContinentalUnit item) 
    { 
     return item.Key ; 
    } 
} 

然後用它

static void Main(string[] args) 
{ 
    var converters = new ConverterCollection(); 
    var toCentimeters = new ConverterToContinentalUnit 
    { 
     Key = "i", 
     Coefficent = 0.3937, 
     PrefixForResult = "In Centimeters" 
    } 

    converters.Add(toCentimeters); 

    WriteLine("Enter the value you wanted to convert: "); 
    int input = ToInt32(ReadLine()); 

    var choiceText = 
     "Press Any Of The Given Choices 
     I->convert from inches to centimeters. 
     G->convert from gallons to liters. 
     M->convert from mile to kilometer. 
     P->convert from pound to kilogram."; 
    WriteLine(choiceText); 

    char choice = Char.ToLower(ToChar(ReadLine())); 

    var converter = converters[choice]; 
    WriteLine(converter.Convert(input)); 

    ReadKey(); 
} 
0

枚舉支持「字節,sbyte,short,ushort,int,uint,long或ulong「。它不支持double或float。但是你可以爲它使用結構。

using System; 
using static System.Console; 
using static System.Convert; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     public struct MyUnits 
     { 
      public const double Centimeter = 0.3037; 
      public const double Liters = 3.78; 
      public const double Kilometer = 1.60; 
      public const double Kilogram = 0.453; 
     } 

     enum MyUnitEnum 
     { 
      Centimeters, 
      Liters, 
      Kilometer, 
      Kilogram, 
     } 

     static void Main(string[] args) 
     { 
      double centimeter, liters, kilometer, kilogram, final = 0; 
      string unitWord; 
      WriteLine("Enter the value you wanted to convert: "); 
      int input = ToInt32(ReadLine()); 
      WriteLine("\n Press Any Of The Given Choices \n I->convert from inches to centimeters." + 
         "\n G->convert from gallons to liters.\n M->convert from mile to kilometer." + 
         "\n P->convert from pound to kilogram."); 

      char choice = Char.ToLower(ToChar(ReadLine())); 

      if (choice == 'i') 
      { 
       final = input/MyUnits.Centimeter; 
       unitWord = MyUnitEnum.Centimeters.ToString(); 
      } 
      else if(choice == 'g') 
      { 
       final = input/MyUnits.Liters; 
       unitWord = MyUnitEnum.Liters.ToString(); 

      } 
      else if (choice == 'm') 
      { 
       final = input/MyUnits.Kilometer; 
       unitWord = MyUnitEnum.Kilometer.ToString(); 
      } 
      else if (choice == 'p') 
      { 
       final = input/MyUnits.Kilogram; 
       unitWord = MyUnitEnum.Kilogram.ToString(); 
      } 
      else 
      { 
       unitWord = "You Enter A Invalid Choice, Please Enter A Valid Choice...!"; 
      } 

      WriteLine("In " + unitWord + final); 
      ReadKey(); 
     } 
    } 
}