在不使用 if-else 子句 12 次的情况下完成此任务的最佳方法是什么?任务是这样的:
if(mon=="1")
{
month="JAN";
}
else if(mon=="2")
{
month="FEB";
}
等等..
在不使用 if-else 子句 12 次的情况下完成此任务的最佳方法是什么?任务是这样的:
if(mon=="1")
{
month="JAN";
}
else if(mon=="2")
{
month="FEB";
}
等等..
尝试使用此代码
using System.Globalization;
var month = 7;
var dtf = CultureInfo.CurrentCulture.DateTimeFormat;
string monthName = dtf.GetMonthName(month);
string abbreviatedMonthName = dtf.GetAbbreviatedMonthName(month);
替代方法是使用数组。
string[] months = new string[]{"JAN", "FEB", "MAR",..., "DEC"};
string month = months[value - 1];
-1
因为索引从零开始。
或者
System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1)
using System.Globalization;
CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames[int.Parse(mon)-1];
使用开关盒:
switch(mon)
{
case "1":
month = "JAN";
break;
case "2":
month = "FEB";
break;
default:
month = string.Empty; // OR throw exception
break;
}
另外的选择:
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
)。