C#——设计一个窗体应用程序,在该程序定义平面图形抽象类和其派生类圆、矩形、和三角形。
该程序实现的功能包括:输入相应图形的参数,如矩形的长和宽,单击相应的按钮,根据输入参数创建图形类并输出该图形的面积。
设计界面:
编写代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 图形面积
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//圆
private void button1_Click(object sender, EventArgs e)
{
Circle c = new Circle(Convert .ToDouble ( textBox1 .Text) );
label4.Text = "圆的面积为:"+c.Area();
}
//矩形
private void button2_Click(object sender, EventArgs e)
{
Trangle t = new Trangle(Convert .ToDouble (textBox1 .Text ),Convert .ToDouble (textBox2 .Text ));
label4 .Text ="矩形的面积为:"+t.Area();
}
//三角形
private void button3_Click(object sender, EventArgs e)
{
S s = new S(Convert .ToDouble (textBox1 .Text ),Convert .ToDouble (textBox2 .Text ));
label4 .Text ="三角形的面积为:"+s.Area();
}
}
//抽象基类
public abstract class Figure
{
public abstract double Area();
}
//圆
public class Circle : Figure
{
double r;
public Circle(double r)
{
this.r = r;
}
public override double Area()
{
return r*r*3.14;
}
}
//矩形
public class Trangle : Figure
{
double length;
double width;
public Trangle(double length,double width)
{
this.length = length;
this.width = width;
}
public override double Area()
{
return length*width ;
}
}
//三角形
public class S : Figure
{
double length;
double width;
public S(double length, double width)
{
this.length = length;
this.width = width;
}
public override double Area()
{
return (length * width)/2;
}
}
}
运行结果: