【发布时间】:2020-04-04 16:56:06
【问题描述】:
我正在尝试打印列表中的 int 项,但我得到以下输出,这显然不是我想要打印的:
YSolution.Dice
YSolution.Dice
YSolution.Dice
YSolution.Dice
YSolution.Dice
源代码:
class Dice
{
//defining variable and properties
private bool _hold = false;
private Random rnd;
public int Current { get; private set; }
public bool IsHolding
{
get { return _hold; }
set { _hold = value; }
}
public Dice()
{
Current = 0;
rnd = new Random(Guid.NewGuid().GetHashCode());
FRoll();
}
public int FRoll()
{
Current = rnd.Next(1, 7);
return Current;
}
class DiceCup
{
public List<Dice> Dices { get; } = new List<Dice>();
public DiceCup(int count)
{
for (int i = 0; i < count; i++)
{
Dices.Add(new Dice());
}
foreach (Dice aDice in Dices)
{
Console.WriteLine(aDice);
}
}
class Program
{
static void Main(string[] args)
{
DiceCup nbd = new DiceCup(count);
}
}
方法 FRoll();由于某种原因,当一个新项目添加到列表中时,似乎没有在骰子类中被调用。我真的只想打印出列表骰子中的项目,但我没有得到我想要的输出/结果。谁能发现错误?
【问题讨论】:
-
Console.WriteLine 使用 Dice 中的
ToString来打印类名称和位置。您可以覆盖 Dice 类中的ToString方法以返回 Current 属性。可以在此处 (docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…) 找到覆盖ToString的文档。