如何缩短以下C#if语句?

时间:2017-03-27 07:01:28

标签: c#

我想缩短以下代码,但我不知道从哪里开始。

交换机是否可以采用这种方式?

        static string RevisedConversionFunction(string input, string from, string to)
    {
        double exchangeRateUSD;
        double exchangeRateAUD;
        double exchangeRateCAD;
        double exchangeRateEUR;
        double exchangeRateGBP;
        double exchangeRateNZD;
        double fromExchangeRate;
        double toExchangeRate;
        exchangeRateUSD = 1;
        exchangeRateAUD = 1.31;
        exchangeRateCAD = 1.28;
        exchangeRateEUR = 0.95;
        exchangeRateGBP = 0.68;
        exchangeRateNZD = 1.36;
        fromExchangeRate = 0;
        toExchangeRate = 0;

        if (from.Equals("USD"))
        {
            fromExchangeRate = exchangeRateUSD;
        }
        if (from.Equals("AUD"))
        {
            fromExchangeRate = exchangeRateAUD;
        }
        if (from.Equals("CAD"))
        {
            fromExchangeRate = exchangeRateCAD;
        }
        if (from.Equals("EUR"))
        {
            fromExchangeRate = exchangeRateEUR;
        }
        if (from.Equals("GBP"))
        {
            fromExchangeRate = exchangeRateGBP;
        }
        if (from.Equals("NZD"))
        {
            fromExchangeRate = exchangeRateNZD;
        }

        if (to.Equals("USD"))
        {
            toExchangeRate = exchangeRateUSD;
        }
        if (to.Equals("AUD"))
        {
            toExchangeRate = exchangeRateAUD;
        }
        if (to.Equals("CAD"))
        {
            toExchangeRate = exchangeRateCAD;
        }
        if (to.Equals("EUR"))
        {
            toExchangeRate = exchangeRateEUR;
        }
        if (to.Equals("GBP"))
        {
            toExchangeRate = exchangeRateGBP;
        }
        if (to.Equals("NZD"))
        {
            toExchangeRate = exchangeRateNZD;
        }

        double amount;
        Double.TryParse(input, out amount);

        amount = (amount / fromExchangeRate) * toExchangeRate;
        amount = Math.Round(amount, 2);

        string result = Convert.ToString(amount);
        return result;
    }

我不熟悉开关,但有没有办法在这种情况下使用它们?

提前致谢, 马特

编辑 - 编辑 - 编辑 - 编辑 - 编辑

谢谢大家的意见。

以下代码是我最终使用的代码:

        static string RevisedConversionFunction(string input, string from, string to)
    {

        //Exchange Rates
        Dictionary<string, double> rates = new Dictionary<string, double>();
        rates.Add("USD", 1);
        rates.Add("AUD", 1.31);
        rates.Add("CAD", 1.28);
        rates.Add("EUR", 0.95);
        rates.Add("GBP", 0.68);
        rates.Add("NZD", 1.36);

        //Conversion
        double amount;
        Double.TryParse(input, out amount);
        return Convert.ToString(Math.Round(((amount / rates[from]) * rates[to]), 2));
    }

6 个答案:

答案 0 :(得分:17)

  • 在这种情况下我会使用词典
  • 使用decimal代替double来阻止舍入问题

代码:

static string RevisedConversionFunction(string input, string from, string to)
{
    Dictionary<string, decimal> dExchange = new Dictionary<string, decimal>()
    { 
        {"USD" , 1},
        {"AUD" , 1.31m},
        {"CAD" , 1.28m},
        {"EUR" , 0.95m},
        {"GBP" , 0.68m},
        {"NZD" , 1.36m}
    };

    if (dExchange.ContainsKey(from) && dExchange.ContainsKey(to))
    {
        return Math.Round((decimal.Parse(input) / dExchange[from]) * dExchange[to], 2).ToString();
    }
    else
    {
        // at least one currency not in the dictionary - exception handling?
        return null; 
    }
}

答案 1 :(得分:2)

我不是c#用户,但我认为最好使用数组

var dictionary = new Dictionary<string, string>
{
    { "USD", "exchangeRateUSD" },
    { "AUD", "exchangeRateAUD" },
    { "CAD", "exchangeRateCAD" }
};

答案 2 :(得分:1)

如果您打算使用if语句,那么您也应该使用其他if语句。你在那里的代码将检查每一个,即使第一个命中。这只会检查第一个(假设第一个是真的)。​​

if (from.Equals("USD"))
    {
        fromExchangeRate = exchangeRateUSD;
    }
else if (from.Equals("AUD"))
    {
        fromExchangeRate = exchangeRateAUD;
    }

将其切换到交换机可能是一个非常好的解决方案:

switch(a) { case 0: ...; break; case 1: ...; break; }

通常任何遇到if..else if ..序列的现代编译器都可以被一个人转换为switch语句,编译器也会这样。

答案 3 :(得分:1)

按如下方式创建映射字典:

public static readonly Dictionary<string, double> currencyMapping = 
    new Dictionary<string, double>
    {
      {"USD",1},
      {"AUD",1.31},
      {"CAD",1.28},
      {"EUR",0.95},
      {"GBP",0.68},
      {"NZD",1.36},   
    }

现在可以按如下方式使用TryGet值或指定默认值。还要注意Dictionary,因为它包含只读信息a static readonly,在构造函数中进行一次运行时评估,然后它不能在程序中的任何地方修改,因此它是一个非常恒定的信息,如一个const,这是编译时间

 double fromExchangeRate;
    if(!currencyMapping.TryGetValue(from,out fromExchangeRate))
      fromExchangeRate = <DefaultValue>

答案 4 :(得分:1)

您可以使用词典。

var exchanges = new Dictionary<string, double>()
{
    ["USD"] = 1,
    ["AUD"] = 1.31,
    ["CAD"] = 1.28,
    ["EUR"] = 0.95,
    ["GBP"] = 0.68,
    ["NZD"] = 1.36,
};

double fromExchangeRate = 0;
double toExchangeRate = 0;

if (exchanges.ContainsKey(from))
{
    fromExchangeRate = exchanges[from];
}
else
{
    // 'from' not in dictionary
}


if (exchanges.ContainsKey(to))
{
    toExchangeRate = exchanges[to];
}
else
{
    // 'to' not in dictionary
}

答案 5 :(得分:-1)

使用数组减少第一行代码 数组总是固定大小,必须这样定义:

<div *ngIf="vehicles">
        <p-dataTable [value]="vehicles.dallases">
            <p-column *ngFor="let col of cols" [field]="col.field" [header]="col.header"></p-column>
        </p-dataTable>
    </div>

<!--Testig out other possibilities-->
    <div *ngIf="vehicles">
        <p-dataTable [value]="vehicles.dallases[0].dallas_list">
            <p-column *ngFor="let col2 of cols2" [field]="col2.field" [header]="col2.header"></p-column>
        </p-dataTable>
    </div>

对于String Data,将其存储在数组中,如

double[] exchangeRate = new double[8];

// This means array is double[3] and cannot be changed without redefining it.
exchangeRate[0] = 1;
exchangeRate[1] = 1.31;
and so on..

然后使用Foreach遍历

String[] Data = new String[8];

// This means array is double[3] and cannot be changed without redefining it.
Data[0] = "USD";
Data[1] = "AUD";
and so on..

根据您的要求,您可以这样做。

希望它对您有用..谢谢: - )