3

在不使用 if-else 子句 12 次的情况下完成此任务的最佳方法是什么?任务是这样的:

if(mon=="1")
{
 month="JAN";
}
else if(mon=="2")
{
 month="FEB";
}

等等..

4

5 回答 5

14

尝试使用此代码

using System.Globalization;

var month = 7;
var dtf = CultureInfo.CurrentCulture.DateTimeFormat;
string monthName = dtf.GetMonthName(month);
string abbreviatedMonthName = dtf.GetAbbreviatedMonthName(month);
于 2012-09-25T05:04:58.280 回答
2

替代方法是使用数组。

string[] months = new string[]{"JAN", "FEB", "MAR",..., "DEC"};
string month = months[value - 1];

-1因为索引从零开始。

或者

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1)
于 2012-09-25T04:58:40.550 回答
2
using System.Globalization;
CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames[int.Parse(mon)-1];
于 2012-09-25T05:13:35.963 回答
1

使用开关盒

switch(mon)
{
    case "1":
            month = "JAN";
            break;
    case "2":
            month = "FEB";
            break;
    default:
            month = string.Empty; // OR throw exception
            break;
}
于 2012-09-25T05:00:24.687 回答
1

另外的选择:

switch (int.parse(mon))
{
    case 1: return "JAN";
    case 2: return "FEB";
    //...
    case 12: return "DEC";
    default: return "???";
}

// Azodious notes that switches work on strings too, so you can also do:
switch (mon)
{
    case "1": return "JAN";
    case "2": return "FEB";
    //...
    case "12": return "DEC";
    default: return "???";
}

mon或作为数组的索引,类似于 John Woo 展示的内容(但您必须首先解析int)。

于 2012-09-25T05:00:54.143 回答