C# 列表中的ArgumentOutOfRange

C# 列表中的ArgumentOutOfRange,c#,unity3d,C#,Unity3d,我有一个Unity3D项目。在这个项目中,我应该在特定的索引号中将一些数据添加到列表中,但它会引发以下错误: ArgumentOutOfRangeException:参数超出范围。参数名称: 索引 这是我的代码: foreach (var Player in PhotonNetwork.PlayerList) { NameList.Clear(); if ((int)Player.CustomProperties["GameCount"] == First) {

我有一个Unity3D项目。在这个项目中,我应该在特定的索引号中将一些数据添加到列表中,但它会引发以下错误:

ArgumentOutOfRangeException:参数超出范围。参数名称: 索引

这是我的代码:

foreach (var Player in PhotonNetwork.PlayerList)
{
    NameList.Clear();
    if ((int)Player.CustomProperties["GameCount"] == First)
    {
        NameList.Insert(0 ,(string)PhotonNetwork.LocalPlayer.CustomProperties["Name"]);
    }
    else if ((int)PhotonNetwork.LocalPlayer.CustomProperties["GameCount"] == Second)
    {
        NameList.Insert(1 ,(string)Player.CustomProperties["Name"]);
    }
    else if ((int)Player.CustomProperties["GameCount"] == Third)
    {
        NameList.Insert(2,(string)PhotonNetwork.LocalPlayer.CustomProperties["Name"]);
    }
    else if ((int)Player.CustomProperties["GameCount"] == Fourth)
    {
        NameList.Insert(3, (string)PhotonNetwork.LocalPlayer.CustomProperties["Name"]);
    }
}

Insert方法如下所示:
公共void Insert(int索引,T项)

异常在两种情况下抛出,如关于ArgumentOutOfRangeException部分所述:

  • 参数
    索引
    小于0
  • 参数
    索引
    大于
    计数
  • 对于您的案例,第一个选项不正确,因为您的所有索引都高于零。然后,这意味着在一个
    中,如果尝试在远远高于现有元素数的位置插入一个值,则会导致异常

    我可以建议您进行一些调试,并在元素较少时进行查看。或者使用
    Add
    而不是
    Insert
    ,您可以找到更多信息

    更新

    例如,当您尝试执行

    NameList.Insert(3, (string)PhotonNetwork.LocalPlayer.CustomProperties["Name"]);
    
    您正试图将一个元素插入到位置
    3
    ,但如果列表中只有1元素,则插入将抛出错误

    如果第一个
    元素(0)
    不插入,但插入第二个
    元素(1)
    则该参数超出范围。示例:如果程序先执行:

    NameList.Insert(2,(string)PhotonNetwork.LocalPlayer.CustomProperties["Name"]);
    
    但没有人执行:

     NameList.Insert(0 ,(string)PhotonNetwork.LocalPlayer.CustomProperties["Name"]);
    

    发布错误消息时,应始终包括引发异常的行。如果名称列表为空,则不能在其他位置插入任何内容。什么都没有。