Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将用户输入存储在列表中会导致索引越界错误_C#_List - Fatal编程技术网

C# 将用户输入存储在列表中会导致索引越界错误

C# 将用户输入存储在列表中会导致索引越界错误,c#,list,C#,List,我试图将用户输入读取到字符串列表中,但在输入第一个值时出错: 索引必须在列表的范围内。参数名称:索引 问题出在游戏中。插入(e,f)它不允许我存储值。当异常发生时,Insert被调用为: games.Insert(1, "test"); 完整代码: static void Main(string[] args) { char g = 'w'; string f; List<string> games = new List<string>()

我试图将用户输入读取到字符串列表中,但在输入第一个值时出错:

索引必须在列表的范围内。参数名称:索引

问题出在
游戏中。插入(e,f)它不允许我存储值。当异常发生时,
Insert
被调用为:

   games.Insert(1, "test");
完整代码:

static void Main(string[] args)
{
    char g = 'w';
    string f;
    List<string> games = new List<string>();
    for (int e = 1; e <= 10; e++)
    {
        Console.WriteLine("what are your favorite game" + e);
        f = (Console.ReadLine()).ToString();
        games.Insert(e, f);
    }

    while (g != 'q')
    {
        Console.WriteLine("A for adding a game Q for quiting");
        g = char.Parse(Console.ReadLine());
        if (g == 'a')
        {
            games.Add(Console.ReadLine());
        }
    }
}
static void Main(字符串[]args)
{
字符g='w';
字符串f;
列表游戏=新列表();
对于(int e=1;e变化


for(int e=1;e问题在循环中,您从1开始,第一次尝试在索引1中插入。但如果列表的大小超过了它的大小,则无法在索引中插入。因此,从0索引开始循环

for (int e = 0; e < 10; e++)
{
    Console.WriteLine("what are your favorite game" + e);
    f = Console.ReadLine();
    games.Insert(e, f);
}
您可以看到,它首先检查索引。

游戏。插入(e,f)将不起作用,因为您无法在不存在的索引上插入项目

Add(f)会起作用,因为Add()方法会按顺序向列表中添加一个项目。它会生成列表的下一个索引并为其分配新值


插入(index,value)只能在您已经使用Add()方法在索引处添加了值的情况下才能工作。请参考

尝试做
游戏。添加(f);
您真的需要
ToString()
?旁注:让
@AlexeiLevenkov是的,只是想修改他的代码中尽可能少的部分。
public void Insert(int index, T item)
{
  if ((uint) index > (uint) this._size)
    ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
  if (this._size == this._items.Length)
    this.EnsureCapacity(this._size + 1);
  if (index < this._size)
    Array.Copy((Array) this._items, index, (Array) this._items, index + 1, this._size - index);
  this._items[index] = item;
  this._size = this._size + 1;
  this._version = this._version + 1;
}