c# - 循环遍历字符串数组以创建这些字符串的类变量

标签 c# loops unity3d

所以我将这段代码放在一个名为 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/

相关文章:

c# - mybatis .NET 可以直接和Oracle ODP.NET 客户端一起使用吗?

c# - 为什么我在使用 IPv6 URI 时得到 'System.UriFormatException: Invalid URI: Invalid port specified.'?

r - 有没有办法对访问向量的多个元素的操作进行向量化?

c# - Unity 中的按钮,不使用 UI?

c# - 如何在 Unity 中全局为类创建别名?

c# - 从 Razor View 中获取绑定(bind) URL

c# - 如何维护 GridView DropDownList 中的选定项

c++ - 计算 2 的幂的意外结果 [C++]

perl - 我们可以在 Perl 中同时运行两个非嵌套循环吗?

android - 检查触摸点是否在 Unity 中的盒子碰撞器内