Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.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_Random - Fatal编程技术网

C# 从列表中获取整数数组的值

C# 从列表中获取整数数组的值,c#,list,random,C#,List,Random,有人能告诉我为什么消息框没有显示随机数的值吗?我试图得到10个随机数,并在消息框中一次显示一个。数字可以重复,并且应该在1到4之间 public void GetRandomPattern() { List<int> pattern = new List<int>(); rounds = 10; Random number = new Random(); f

有人能告诉我为什么消息框没有显示随机数的值吗?我试图得到10个随机数,并在消息框中一次显示一个。数字可以重复,并且应该在1到4之间

public void GetRandomPattern()
        {
            List<int> pattern = new List<int>();

            rounds = 10;
            Random number = new Random();

            for (int counter = 0; counter < rounds; counter++)
            {
                pattern.Add(number.Next(1, 4));
                MessageBox.Show(pattern.ToString());
            }
        }
模式是一个列表。当你这么做的时候,它是在整个对象上的,即所有的项目,而不仅仅是一个。列表不提供显示项目的方法,所以它只返回类型

要一次显示一个数字,您需要执行以下操作:

pattern[counter].ToString()
这将选择列表中的特定项,因为计数器与列表的当前索引匹配。

如果未覆盖,ToString将显示对象类型的名称。在您的情况下,它将显示列表类型的名称:

System.Collections.Generic.List`1[System.Int32]

若要显示列表的内容,应手动创建字符串。例如

 var formattedPattern = String.Join(", ", pattern); // "2, 1, 3, 2"
 MessageBox.Show(formattedPattern );
如果您想在每次迭代中显示列表中的各个项目,可以按照@MikeH的建议按索引引用它们,或者只使用一个临时变量

 var nextNumber = number.Next(1, 4);
 pattern.Add(nextNumber);
 MessageBox.Show(nextNumber.ToString());

您正试图在消息框中显示列表对象。相反,请尝试下面的代码

 for (int counter = 0; counter < rounds; counter++)
            {
                var randNo = number.Next(1, 4);
                pattern.Add(randNo );
                MessageBox.Show(randNo);
            }

什么是模式?我添加了模式代码,对不起。这是一个整数列表。请尝试:MessageBox.Showstring.join、、pattern.Selectx=>x.ToString;因为您显示的是列表,而不是号码?谢谢@迈克,这就是我想做的。工作完美。我很感激所有的答案。