设置显示方法以显示来自对象的数据

时间:2014-02-24 02:49:20

标签: c#

private void shapeBuilderButton_Click(object sender, EventArgs e)
{
    // Objects of shapes

    Rectangle rectangle1 = new Rectangle(20, 30);
    Square square1 = new Square(25, 35);
    Triangle triangle1 = new Triangle(20, 10);
    Square square2 = new Square(9);

    // I know that I can display the information this way
    // but I'd like to create a method to do this

    labelDisplayRectangle.Text = "Width: " + rectangle1.Width + " Height: " + rectangle1.Height + " Area: " + rectangle1.ComputeArea();
    labelDisplaySquare.Text = "Width: " + square1.Width + " Height: " + square1.Height + " Area: " + square1.ComputeArea();
    labelDisplayTriangle.Text = "Width: " + triangle1.Width + " Height: " + triangle1.Height + " Area " + triangle1.ComputeArea();
    labelDisplaySquare.Text = " Side: " + square2.Width + " Side: " + square2.Height + " Area: " + square2.ComputeArea();

    // I want to print my object rectangle1 with the format located in Display.

    Display(rectangle1);
    Display(square1);
    Display(square2);
    Display(triangle1);
}

// How do I set up this method to do that?

public void Display()
{
    labelDisplayRectangle.Text = "Width: " + width + " Height: " + height + " Area: " + area; 
}

1 个答案:

答案 0 :(得分:1)

我假设所有类都继承自公共基类(例如:Shape)或实现接口。如果你可以这样定义你的方法:

public void Display(Shape shape, Label lbl)
{
    lbl.Text = string.Format("Width:  {0} Height: {1} Area: {2}",
                                shape.Width,shape.Height, shape.ComputeArea());
}

你可以这样称呼它:

Display(rectangle,labelDisplayRectangle);
Display(square1,labelDisplaySquare);
Display(triangle1,labelDisplayTriangle);

此外,如果您为基类覆盖ToString方法,则会更容易。然后您只需要在Shape实例上调用ToString方法来获取Shape的字符串表示。