【问题标题】:How to fix Console Writing the name of the Class? [duplicate]如何修复控制台写入类的名称? [复制]
【发布时间】:2019-04-13 01:49:09
【问题描述】:

我是 C# 新手,几个小时以来我一直在为此苦苦挣扎,希望能得到您的帮助。

我想创建一个多边形并记下点的每个位置。

目前我有这个: -班级点

class Point
{
    private int x;
    private int y;


    public Point(int x2, int y2)
    {
        x = x2;
        y = y2;
    }
}

-类多边形

class Polygon
{
    private Point[] Points;

    public Polygon(params Point[] a)
    {
        Points = new Point[a.Length];
        for (int i = 0; i < a.Length; i++)
        {
            Points[i] = a[i];
        }
    }

    public Point this[int index]
    {
        get { return Points[index]; }
        set { Points[index] = value;}
    }
}

现在我主要有这个:

        Polygon First= new Polygon(new Point(7,4), new Point(4,1), new Point(2, 1));

        First[0] = new Point(3, 4);

        Console.WriteLine("points of polygon ");
        for (int i = 0; i < First.PointCounter; i++)
        {
            Console.WriteLine(First[i]);
        }

但现在我在控制台中看到的是“多边形点”之后点的每个位置,而不是看到:https://imgur.com/Z5aVFMK

应该是什么样子:https://imgur.com/a/aFkdrEF

应该是什么样子:https://imgur.com/a/aFkdrEF

【问题讨论】:

  • 你需要知道的一件事:override string ToString()

标签: c# indexer


【解决方案1】:

我添加了ToString 的覆盖,以便您的Point 类在转换为字符串时具有预期的输出。像"x:3 y:4" 这样的输出。

class Point
{
    public int x { get; private set; }
    public int y { get; private set; }

    public Point(int x2, int y2)
    {
        x = x2;
        y = y2;
    }

    public override string ToString()
    {
        return $"x:{x,-3} y:{y,-3}";
    }
}

就目前而言,它是成为struct 而不是class 的理想人选。

【讨论】:

  • 非常感谢您的帮助,先生。成功了!。
  • 不客气,我的朋友!我将不胜感激。 :-)
  • @MickyD 你是对的。我更新了我的答案。
【解决方案2】:

C# 不像其他语言那样被“解释”,因此Console.WriteLine 方法不会猜出您要打印的内容。

要使用当前代码提供您正在寻找的结果,您必须为您的 Point 类提供公共属性:

public int X { get { return x;} set{ x = value;} }
public int Y { get { return y;} set{ y = value;} }

之后,您现在可以在 for 循环中访问这些属性:

for (int i = 0; i < First.PointCounter; i++)
{
    Console.WriteLine($"x:{First[i].X}    y:{First[i].Y}");
}

【讨论】:

  • 提供带有 .ToString() 覆盖的解决方案,这对于这种情况似乎也很好。
  • @CoderofCode 我个人并不热衷于重写.ToString() 方法。但是,如果您想在此处添加它,请继续。
  • ToString() 有合法用例。
  • @MickyD 绝对。我只是不热衷于将其作为对语言新手的答案,因为滥用它会导致从 exp. 开始非常困难的调试。但无论哪种方式,Theodor Zoulias 的解决方案都有效。
  • “语言新手” - 是的,非常棒。通过提供属性,可以更清楚地了解正在发生的事情。 +1 好先生
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
  • 2019-09-26
  • 2020-05-24
  • 1970-01-01
  • 2017-09-24
  • 2014-02-14
相关资源
最近更新 更多