所以我将这段代码放在一个名为 SchoolData 的 .cs 文件中,该文件包含一个类和一个列表。
public static List<YearGroupsData> yearGroupsDataList = new List<YearGroupsData>();
public class YearGroupsData
{
public int id { get; set; }
public int year { get; set; }
public string groupName { get; set; }
public int subject { get; set; }
}
但是,我正在尝试在另一个 .cs 脚本中使用一个循环来建立网络连接并从网站获取数据,我没有包括连接信息或一些脚本,因为这不是'这部分出错了......
private IEnumerator ViewYearGroups()
{
//Some code for connection here
yield return viewYearGroups;
string yearGroupsDataString = viewYearGroups.text;
yearGroups = yearGroupsDataString.Split(';');
foreach (string yearGroup in yearGroups)
{
YearGroupsData yearGroupsData = new YearGroupsData()
{
id = Int32.Parse(GetDataValue(yearGroup, "Id:")),
year = Int32.Parse(GetDataValue(yearGroup, "Year:")),
groupName = GetDataValue(yearGroup, "GroupName:"),
subject = Int32.Parse(GetDataValue(yearGroup, "Subject:")),
};
SchoolData.yearGroupsDataList.Add(yearGroupsData);
}
}
GetDataValue 是搞砸的部分。它给了我 ArgumentOutOfRangeException,我不确定为什么。如果我不在循环中使用它,它会起作用,我也尝试了一个 for 循环,但仍然一样,有人知道发生了什么吗?
public string GetDataValue(string data, string index)
{
string value = data.Substring(data.IndexOf(index) + index.Length);
if (value.Contains("|"))
{
value = value.Remove(value.IndexOf("|"));
}
return value;
}
最佳答案
在您的 GetDataValue() 方法中添加一个 try catch 以帮助调试。如果它在没有 foreach 循环的情况下工作,那么我的猜测是您正在迭代的字符串对象之一与您可能期望的不同。 https://msdn.microsoft.com/en-us/library/system.argumentoutofrangeexception(v=vs.110).aspx
try
{
string value = data.Substring(data.IndexOf(index) + index.Length);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
关于c# - 循环遍历字符串数组以创建这些字符串的类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50519327/