public string subs(string s, int start, int length)
{
string pom = "";
for (int i = start; i < (start+length); i++)
pom += s[i];
return pom;
}
protected void Page_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(@"E:\matura\web\b17\WebApplication1\WebApplication1\aseti\A8vebprodavnica.txt");
string linija = sr.ReadLine();
while(linija != null)
{
string pom = subs(linija, 0, 6);
if (DropDownList1.Items.FindByText(pom) == null)
DropDownList1.Items.Add(pom);
linija = sr.ReadLine();
}
}
在
pom += s[i];
行的“subs”功能中,我的索引超出了范围。有人能解释一下这是怎么发生的吗?
我做的第一件事是尝试使用已经实现的 C# 函数作为子字符串,但我遇到了同样的错误,然后我编写了自己的函数。
将
subs()-method
替换为:
public string subs(string s, int start, int length)
{
if(start < 0 || length < 0 || start + length > s.Length)
{
throw new ArgumentOutOfRangeException("Start or length is out of range");
}
return s.Substring(start, length);
}