请给我解释一下

时间:2017-08-01 18:18:21

标签: c#

StringBuilder sb = new StringBuilder();

for (int i = 0; i < daysOfWeek.Length; i++)
{
    sb.Append(daysOfWeek[i]);
    if (i < daysOfWeek.Length - 2)
        sb.Append(", ");
    else if (i == daysOfWeek.Length - 2)
        sb.Append(" and ");
}

Console.WriteLine(sb.ToString());

我理解这段代码中的所有内容,除了daysOfWeek.Length

之后-2的作用

从中减去2是什么?

3 个答案:

答案 0 :(得分:1)

然而,如果我不得不猜测,那么daysOfWeek阵列中的i很多天应该是Sun Mon Tue Wed等。 -2从该数字中减去,然后与7 - 2所在的迭代进行比较。我对C#不是很熟悉,但是如果数组一周有7天,它应该是0。由于Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday是数组中的第一个位置,这意味着它应该打印类似SELECT ActivationTime, COUNT(DISTINCT NodeID) NumberOfID FROM CASCADING GROUP BY ActivationTime

的内容

答案 1 :(得分:0)

void Main()
{
    var daysOfWeek = GetDaysOfWeek();
    MethodA(daysOfWeek);
    MethodB(daysOfWeek);
}

void MethodA(string[] daysOfWeek)
{
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < daysOfWeek.Length; i++)
    {
        sb.Append(daysOfWeek[i]);

        if (i < daysOfWeek.Length - 2)
            sb.Append(", ");
        else if (i == daysOfWeek.Length - 2)
            sb.Append(" and ");
    }

    Console.WriteLine(sb.ToString());
}

void MethodB(string[] daysOfWeek)
{
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < daysOfWeek.Length; i++)
    {
        sb.Append(daysOfWeek[i]);

        if (i < daysOfWeek.Length)
            sb.Append(", ");
    }

    Console.WriteLine(sb.ToString());
}

public string[] GetDaysOfWeek()
{
    return (new List<string>{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}).ToArray() ;
}

美化。它坚持&#34;和&#34;在一周的最后一天之前进入字符串构建器。

  

方法A:星期日,星期一,星期二,星期三,星期四,星期五和星期六

     <方法B:周日,周一,周二,周三,周四,周五,周六,

下次你对这样的简单代码有疑问时,试试吧!看看它做了什么。创建一个类似我上面创建的小程序,并在Visual Studio或Linqpad中运行它。

答案 2 :(得分:0)

int i是用于迭代daysOfWeek

的索引

在C#中,数组基于零,这意味着数组的第一个元素是MyArray[0]

MyArray.Length返回数组中元素的数量,从一开始。

如果您的数组只有1个元素,则.Length为1;你不能做MyArray[MyArray.Length]因为那会引起异常;你做MyArray[MyArray.Length - 1]所以你对你的长度“零基础”。

这是你的评论圈:

for (int i = 0; i < daysOfWeek.Length; i++)
{
    sb.Append(daysOfWeek[i]);
    if (i < daysOfWeek.Length - 2) //If the element is not the last or the penultimate do something
        sb.Append(", ");
    else if (i == daysOfWeek.Length - 2) //if the element is the penultimate of my array, instead of a "comma", put an "and".
        sb.Append(" and ");
}