课程名称 C#程序设计
实验名称 实验一
叁、第三题
一、实验题目
编写一个矩形类(Rect)与一个圆类(Circle),分别通过构造方法对一个矩形对象(rect1)与一个圆对象(circle1)进行初始化后,求出矩形与圆的面积。
二、实验要求
同时具有如下功能:可以设置和读取矩形的边长和圆的半径,但只能读取它们的面积,不能修改面积。
三、实验代码以及执行结果
1、Rect类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 第三题
{
class Rect
{
private double length; //矩形的长
private double width; //矩形的宽
public Rect(double length,double width)
{
this.length = length;
this.width = width;
}
public double Length { get => length; set => length = value; }
public double Width { get => width; set => width = value; }
public double getArea() //获取矩形的面积
{
return length * width;
}
}
}
2、Circle类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 第三题
{
class Circle
{
const double PI = 3.1415;
private double radius; //圆的半径
public Circle(double radius)
{
this.radius = radius;
}
public double Radius { get => radius; set => radius = value; }
public double getArea() //获取圆的面积
{
return radius * radius * PI;
}
}
}
3、主类:
using System;
namespace 第三题
{
class Program
{
static void Main(string[] args)
{
Rect rect1 = new Rect(2, 4);
Console.WriteLine("react1的面积为:{0}",rect1.getArea());
rect1.Length = 4;
rect1.Width = 8;
Console.WriteLine("react1的面积为:{0}", rect1.getArea());
Circle circle1 = new Circle(2);
Console.WriteLine("circle1的面积为:{0}", circle1.getArea());
circle1.Radius = 4;
Console.WriteLine("circle1的面积为:{0}", circle1.getArea());
}
}
}
4、执行结果:
四、实验总结
通过这次实验,我学会了如何快速生成属性的get set 方法