可读性最重要的应该是明显的名称。
i 和 j不是最明显的,但对于简单的情况可能没问题。考虑这个(诚然有些考虑不周)的例子;
static void Main(string[] args)
{
for(int i = 0; i < 100; i++)
for (int j = 0; j < 100; j++)
for (int k = 0; k < 100; k++)
Console.WriteLine("" + i + "-" + j + "-" + k);
}
对比
static void Main(string[] args)
{
for(int survey = 0; survey < 100; survey++)
for (int question = 0; question < 100; question++)
for (int option = 0; option < 100; option++)
Console.WriteLine("" + survey + "-" + question + "-" + option);
}
很容易看出哪个更有意义。但是,当我们这样做时,如何使它更具可读性,同时进一步消除您的命名问题?
static void Main(string[] args)
{
for(int survey = 0; survey < 100; survey++)
PrintSurvey(survey);
}
private static void PrintSurvey(int survey)
{
for (int question = 0; question < 100; question++)
PrintQuestion(survey, question);
}
private static void PrintQuestion(int survey, int question)
{
for (int option = 0; option < 100; option++)
PrintOption(survey, question, option);
}
private static void PrintOption(int survey, int question, int option)
{
Console.WriteLine("" + survey + "-" + question + "-" + option);
}
对于这个简单的循环,可能有点矫枉过正/冗长,只是想说明有更多方法可以处理嵌套循环的命名问题,而不仅仅是找到唯一的名称。