2014-02-24 30 views
0
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; 
} 
+0

您是否創建了「Square」和「Triangle」? –

+0

是的,我創建了所有的單獨的類。也許我會發布我的所有代碼,以便更清楚。 – user3308294

回答

1

我承擔所有的類都來自一個共同的基類繼承(爲前:Shape)介紹我的數據,或者實現了interface.If這樣你就可以這樣定義你的方法:

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方法爲你的基類,這將是easier.Then你只需要撥打ToString方法在您的Shape實例上獲取Shape的字符串表示形式。