如何缩短以下C#条件语句?

3

我希望能够缩短下面的代码,但是我不知道从哪里开始。

使用switch语句是否适合这种情况?

        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));
    }

我不是C#用户,但我认为最好使用数组和循环语句。var dictionary = new Dictionary<string, string> { { "USD", "exchangeRateUSD" }, { "AUD", "exchangeRateAUD" }, { "CAD", "exchangeRateCAD" } }; - Robert Anthony S. Tribiana
6个回答

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; 
    }
}

已保存。太棒了! - Ave
为什么要使用十进制,双精度或者单精度浮点数呢?这并不是典型的金融/科学计算。 - Mrinal Kamboj
2
在处理货币时应始终使用“decimal” - 否则可能会遇到舍入问题。 - fubo
如果需要精度高的话,就需要这样做,否则对于这种操作肯定会有内存影响。 - Mrinal Kamboj
好的回答。唯一需要提醒的是,dExchange 应该在 RevisedConversionFunction 之外声明,否则每次调用函数时都会重新创建它。 - David Arno
1
@DavidArno货币汇率每天都在多次变化,所以我认为将它们保留在源代码中是一个不好的主意... - fubo

2

我不是c#用户,但我认为使用数组会更好。

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

1
我认为最好使用数组和循环语句。请提供“Dictionary”的代码。它是哪个? - Guy

1
如果你要使用if语句,也应该加上else if。你现在的代码会检查每一个if,即使第一个if已经匹配成功了。这个代码只会检查第一个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语句,编译器也会这样做。

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包含只读信息,因此它是static readonly,用于构造函数中的一次运行时评估,然后它不能在程序中任何地方修改,因此它类似于编译时常量。请保留HTML标签。
 double fromExchangeRate;
    if(!currencyMapping.TryGetValue(from,out fromExchangeRate))
      fromExchangeRate = <DefaultValue>

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
}

-1

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

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..

对于字符串数据,请将其存储在数组中,如下所示:

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..

然后使用Foreach遍历

foreach (String[] row in Data)
{
    if(from.Equals(Data[0]))
    {
       //Do something
    }
}

根据您的需求,您可以以同样的方式进行操作。

希望这对您有所帮助。谢谢 :-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接