早教吧 育儿知识 作业答案 考试题库 百科 知识分享

(急用)创建一个Rectangle类,提供属性Length和Width,它们的默认值均为1.该类提供以下public方法:1.Perimeter方法,计算矩形的周长.2.Area方法,计算矩形的面积.3.IsSuqare方法,判断矩形是否是一个正方形.

题目详情
(急用)创建一个Rectangle类,提供属性Length和Width,它们的默认值均为1.该类提供以下public方法:
1.Perimeter方法,计算矩形的周长.
2.Area方法,计算矩形的面积.
3.IsSuqare方法,判断矩形是否是一个正方形.
属性的set方法应该确保不会将属性Length和Width设置为负值.
▼优质解答
答案和解析
/* C#版 */
class Rectangle
{
private Double _length;
private Double _width;
public Double Length
{
get { return _length; }
set { if (value < 0) throw new Exception("Length不能为负"); _length = value; }
}
public Double Width
{
get { return _width; }
set { if (value < 0) throw new Exception("Width不能为负"); _width= value; }
}
public Double Perimeter()
{
return 2 * (Length + Width);
}
public Double Area()
{
return Length * Width;
}
public Boolean IsSuqare()
{
return Length == Width;
}
}