【发布时间】:2015-04-27 20:34:45
【问题描述】:
这里是 C# 菜鸟,尝试用不同的方法解决一个基本问题。我想将一个参数传递给一个方法,并在该方法中循环遍历几个月的数组。如果参数等于数组的位置,我想返回那个数组位置的字符串。
我尝试了以下方法:
class Month
{
private int month;
public string strMonth(int month)
{
this.month = month;
string[] months = { " ", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
for (int i = 0; i < months.Length; i++)
{
if (month == Array.IndexOf(months, i))
{
return months[i];
}
}
return "check fails";
}
}
对于我正在使用的驱动程序
class Program
{
static void Main(string[] args)
{
Month testMonth = new Month();
Console.WriteLine(testMonth.strMonth(2));
Console.ReadKey();
}
}
但是,我总是在控制台中登录check fails。我是在正确的道路上还是菜鸟占了上风,而我这样做完全错了?我也对块级作用域感到困惑(我认为这就是 C# 所做的?)。我来自 JS 背景,习惯于函数级别范围。即使我的检查通过,添加return "check fails" 是否总是会执行?
【问题讨论】:
-
您知道“一月”必须插入 0 对吗?
-
是的,我知道这一点。我有一个空字符串作为 [0] 来欺骗支票。谢谢你指出这一点。不过,这与我的问题无关。