参数超出范围异常,该怎么做

时间:2016-04-26 12:34:00

标签: arrays list range

我正在尝试制作黑客游戏,我有自己的cmd,在那里我输入了commnads,但我遇到了这个问题而且我不知道我做错了什么。

这是Program.cs中的第一个代码

if (enter == "del" + space + FIles.files1[0] && admin == true && connected == true && cdMain == true )
            {
                FIles.files1.RemoveAt(0);

                Console.WriteLine("");
                FIles.files1.ForEach(Console.WriteLine);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine(successfull);
                Console.ForegroundColor = ConsoleColor.Green;
            }
            if (enter == "del" + space + FIles.files1[1] && admin == true && connected == true && cdMain == true)
            {
                FIles.files1.RemoveAt(1);

                Console.WriteLine("");
                FIles.files1.ForEach(Console.WriteLine);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine(successfull);
                Console.ForegroundColor = ConsoleColor.Green;
            }
if (enter == "del" + space + FIles.files1[2] && admin == true && connected == true && cdMain == true)
            {
                FIles.files1.RemoveAt(2);

                Console.WriteLine("");
                FIles.files1.ForEach(Console.WriteLine);
               // FIles.files1.AddRange(1);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine(successfull);
                Console.ForegroundColor = ConsoleColor.Green;

            }
            if (enter == "del" + space + FIles.files1[3] && admin == true && connected == true && cdMain == true )
            {
                FIles.files1.RemoveAt(3);

                Console.WriteLine("");
                FIles.files1.ForEach(Console.WriteLine);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine(successfull);
                Console.ForegroundColor = ConsoleColor.Green;
            }

这里是List的第二个

class FIles
{
    public static List<string> files1 = new List<string>();

    public static void Files1()
    {
        files1.Add("file1.exe");
        files1.Add("file2.exe");
        files1.Add("file3.exe");
        files1.Add("file4.exe");
        files1.Add("file5.exe");
    }

}

当我尝试删除thirth时出现错误,请帮助。

1 个答案:

答案 0 :(得分:0)

这个怎么样:

for(int i = 0; i < ExampleList.Count; i++)
{
    if (enter == "del" + space + FIles.files1[i] && admin == true && connected == true && cdMain == true )
    {
            FIles.files1.RemoveAt(i);

            Console.WriteLine("");
            FIles.files1.ForEach(Console.WriteLine);
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine(successfull);
            Console.ForegroundColor = ConsoleColor.Green;
     }
}

您的代码存在的问题是,每次拨打RemoveAt时,列表的大小都会发生变化。两次通话后,您的列表大小为3,FIles.files1[3]超出范围。