我试图在c#(Visual Studio 2010-windows表单应用程序)中编写程序,该程序使用Rectangle类计算矩形的面积和周长。 我有form1有2个文本框(矩形的长度和宽度)和2个标签与结果(区域和周长)。这是代码:
namespace Rectangle
{
public partial class Form1 : Form
{
Rectangle r;
public Form1()
{
InitializeComponent();
}
private void btnArea_Click(object sender, EventArgs e)
{
if (txtWidth.Text.Length == 0 || txtLength.Text.Length == 0)
MessageBox.Show("Insert something in the textboxes!", "Attention!");
else
lblArea.Text = r.Area().ToString();
}
private void btnPerimeter_Click(object sender, EventArgs e)
{
//r.width = Convert.ToInt32(txtWidth.Text);
//r.length = Convert.ToInt32(txtLength.Text);
if (txtWidth.Text.Length == 0 || txtLength.Text.Length == 0)
MessageBox.Show("Insert something in the textboxes!", "Attention!");
else
lblPerimeter.Text = r.Perimeter().ToString();
}
}
}
我的班级代码是:
namespace Rectangle
{
class Rectangle
{
static int length, width;
public int Length
{
get { return length; }
set { length = value; }
}
public int Width
{
get { return width; }
set { width = value; }
}
public int Perimeter()
{
return 2 * (length + width);
}
public int Area()
{
return length * width;
}
}
}
我在这一行有一个例外("Object reference not set to an instance of an object"
):
lblPerimeter.Text = r.Perimeter().ToString();
lblArea.Text = r.Area().ToString();
如何解决?该程序不会计算周边区域。 谢谢4帮助!
答案 0 :(得分:4)
您必须从矩形类创建一个实例,如下所示:
<!-- language: c# -->
Rectangle r = new Rectangle();