-4

如何在 C# 中调用方法?GetArea & GetPerimeter 是我需要调用的方法。

这是我正在处理的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyRectangle

class Rectangle
{
    // Set private variables
    private int _height=0;
    private int _width=0;
    // Accessors
    public int Height{
        set { _height = 6; }
        get { return _height;}
    }
    public int Width {
        set { _width =8; }
        get { return _width;}
    }

    //Public

        public int GetArea()
            {
            return (_width * _height);
            }

            public int GetPerimeter()
            {
            return ((2 * _width) + (2 * _height));
            } 


}
Console.Write("Height is " + Height);
Console.Write("Width is " + Width);
Console.Write.GetArea() 
Console.Write.GetPerimeter() 

}

控制台是显示输出以进行调试的地方。我不确定在哪里调用这些方法。

谢谢!

4

2 回答 2

0

好吧,你可以在任何合法的地方调用它。但是您似乎缺少主要功能和不正确的方法调用语法:

public static void Main() {
   Rectangle rect = new Rectangle();'
   rect.Height = 200;
   rect.Width = 100;

   Console.WriteLine("Height is " + rect.Height);
   Console.WriteLine("Width is " + rect.Width);
   Console.WriteLine(rect.GetArea());
   Console.WriteLine(rect.GetPerimeter());
}

此外,正如 Kevin 所指出的,您需要先拥有一个Rectangle实例,然后才能执行任何操作。

于 2013-05-26T16:33:12.980 回答
0

您需要Rectangle使用new关键字创建类的实例。对于控制台应用程序,这可以在您的main().

这听起来像是家庭作业。如果是这样,我会建议进入教科书一些。这是面向对象编程的一些基础知识。

于 2013-05-26T16:33:41.887 回答