Skip to main content
 首页 » 编程设计

c#之如何缩短代码

2024年02月13日16arxive

我可以缩短这段代码吗?我不想为每个组合都进行从 USD、EUR、CHF、GBP 到 USD、EUR、CHF、GBP 的所有组合,因为代码对于所有转换来说都太长了。

if (Convert.ToString(comboBoxInputMoney.Text) == "USD") 
{ 
    if (Convert.ToString(comboBoxOutputMoney.Text) == "EUR") 
    { 
        double USD = double.Parse(textBoxInputMoney.Text); 
        USD = USD * 0.74; 
        textBoxResultMoney.Text = USD.ToString() + " EUR "; 
    } 
} 
 
if (Convert.ToString(comboBoxInputMoney.Text) == "USD") 
{ 
    if (Convert.ToString(comboBoxOutputMoney.Text) == "CHF") 
    { 
        double USD = double.Parse(textBoxInputMoney.Text); 
        USD = USD * 0.92; 
        textBoxResultMoney.Text = USD.ToString() + " CHF "; 
    } 
} 

请您参考如下方法:

您可以使用字典来存储输入的货币和汇率:

var dict = new Dictionary<string, Dictionary<string, decimal>>(); 
var usDict = new Dictionary<string, decimal>(); 
usDict.Add("EUR", 0.74m); 
usDict.Add("CHF", 0.92m); 
dict.Add("USD", usDict);  
// and so on ... 

您不需要总是创建它,您可以重复使用它并在发生变化时更新汇率。那么输入或输出货币的数量并不重要。

这始终是相同的代码:

Dictionary<string, decimal> currencyExchange; 
if (dict.TryGetValue(comboBoxInputMoney.Text, out currencyExchange)) 
{ 
    decimal rate; 
    decimal value; 
    if(decimal.TryParse(textBoxInputMoney.Text, out value) 
      && currencyExchange.TryGetValue(comboBoxOutputMoney.Text, out rate)) 
    { 
        textBoxResultMoney.Text = string.Format("{0} {1}" 
            , value * rate  
            , comboBoxOutputMoney.Text); 
    } 
}