Index was outside the bounds of the array.

背景今天写了这么一个函数:
private string DateFormatConversion(string str)
        {
                string year = "";
                char[] pstr = str.ToCharArray();
                for (int k = 0; k < 4; k++)
                {
                    year += pstr[k];
                }
                return year;
        }
当str传入值如空的时候,就会提示“Index was outside the bounds of the array.”错误。
解决方案:
在处理str之前,先判断str.Length是否大于零

你可能感兴趣的:(Index was outside the bounds of the array.)