c# - C#:如何将随机 int 值分配给变量?
问题描述
我制作了一个骰子类,其中包含一个使用 random.next 确定 1-6 的随机 int 值的方法。
Fairdice.cs
:
class FairDice
{
//defining variable and property
private Random rnd;
public int Current { get; private set; }
public FairDice()
{
rnd = new Random(Guid.NewGuid().GetHashCode());
Current = 0;
}
public int FRoll()
{
Current = rnd.Next(1, 7);
return Current;
}
RollDice.cs
具有用于打印的循环。
static class RollDice
{
public static void Roll(this int count, Action action)
{
for (int i = 0; i < count; i++)
{
action();
}
}
}
Program.cs
包括此代码,它打印出 1-6 之间的 5 个随机值:
FairDice fd = new FairDice();
5.Roll(() => Console.WriteLine("Dice: " + fd.FRoll()));
问题:我希望在每个变量中分配随机值并将它们存储并保存在列表或数组中以供将来使用。
澄清:
假设它打印出数字:1, 2, 3, 4, 5
-然后我希望为每个值分配一个变量:a = 1, b = 2, ... f = 5
。
和/或简单地将值存储在数组中{1, 2, 3, 4, 5}
有没有办法做到这一点?
解决方案
如果要存储调用返回的值,FRoll
则可以执行以下操作:
FairDice fd = new FairDice();
var numbers = new List<int>();
5.Roll(() => numbers.Add(fd.FRoll())); // Append the values to the list as we generate them
var firstNumberRolled = numbers[0]; // Access the values later
Console.WriteLine($"The first number rolled was {firstNumberRolled}");