【问题标题】:C#: Why does my list not print the items? [duplicate]C#:为什么我的列表不打印项目? [复制]
【发布时间】: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();由于某种原因,当一个新项目添加到列表中时,似乎没有在骰子类中被调用。我真的只想打印出列表骰子中的项目,但我没有得到我想要的输出/结果。谁能发现错误?

【问题讨论】:

标签: c# list random printing


【解决方案1】:

目前您只是在您的 Dice 对象上调用 ToString()。由于您没有覆盖ToString(),这只是使用默认的object.ToString() 实现,它返回对象的类型名称(在您的情况下为YSolution.Dice)。

你的骰子上有一个Current 属性,它返回骰子的值,如果你调用这个方法,那么它将返回骰子的值,然后你可以打印:将Console.WriteLine(aDice); 更改为Console.WriteLine(aDice.Current); .

或者,正如其他人指出的那样,you can override ToString() 在您的 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;
    }

    public override string ToString()
    {
        return Current.ToString();
    }
}

【讨论】:

    【解决方案2】:

    你想实现 ToString 方法:

    public string ToString()
    {
      return Current.ToString();
    }
    

    【讨论】:

      【解决方案3】:

      除了覆盖ToString 方法外,如其他答案中所述,您还可以从骰子中收集结果并打印出来:

      foreach (int result in Dices.Select(d => d.Current))
      {
          Console.WriteLine(result);
      }
      

      Select 方法在 System.Linq 命名空间中定义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-25
        • 2017-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多