switch 문을 사용하여 사용자 입력 유형에 따라 변환을 수행하기 위해 아래 코드를 사용하고 있습니다. 여기서 switch 문 대신 "enum"과 "struct"를 사용할 수 있습니까?
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();
}
}
}
문 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();
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다