如何通过读取用户输入将变量添加到我的列表中?

How can i add variables to my List by reading the User Input?

我是 C# 的初学者,想通过添加到我的列表中。读取用户的输入。

class Program
{
    static void Main(string[] args)
    {
        List<int> list = new List<int>();


        Console.WriteLine("Asking a random Question here");

        // lacking Knowledge here **
         ** = Convert.ToInt16(Console.ReadLine());

        Console.ReadKey();
    }

我想你想要

list.Add(Convert.ToInt32(Console.ReadLine()));

int是一个32位的数字,对应于System.Int32;

class Program
{
static void Main(string[] args)
{
    List<int> list = new List<int>();


    Console.WriteLine("Asking a random Question here");

    // lacking Knowledge here **
     ** = Convert.ToInt16(Console.ReadLine());

    Console.ReadKey();
}

Console.ReadLine() 方法执行 return 一个字符串值,在您的情况下,您希望将用户输入的值添加到您的 int 列表中。

所以基本上你必须:

Int32 number = Convert.ToInt32(Console.ReadLine());

然后按如下方式将号码添加到您的列表中:

list.Add(number);

因此,为了给出问题的详细示例,这里有一个程序可以计算标准输入中列出的数字的平均值,每行一个。它还展示了如何将给定号码添加到列表中。

    using System;
    using System.Collections.Generic;

    namespace AverageNumbers
    {
        class MainClass
        {
            public static void Main (string[] args)
            {
                // Here is the list of numbers
                List<int> numbers = new List<int>();

                // Here are two variables to keep track
                // of the input number (n), and the sum total (sum)
                int n, sum = 0;
                // This while loop waits for user input and converts
                // that input to an integer
                while (int.TryParse(Console.ReadLine(), out n))
                {
                    // Here we add the entered number to the sum
                    sum += n;
                    // And to the list to track how many we've added       
                    numbers.Add(n);
                }

                // Finally we make sure that we have more than 0 numbers that we're summing and write out their average
                Console.WriteLine("Average: " + (numbers.Count > 0? sum / numbers.Count : 0));
            }
        }
    }