类与继承
C# 使用窗口实现交互
1.创建一个圆柱体类:
(1)包含私有字段半径和高,并设置其属性,要求半径和高必须是大于0的数;
(2)包含求表面积和体积的方法;
(3)有无参和有参的构造函数;
(4)包含一个能输出圆柱体信息的方法。
创建一个圆柱体数组,并为数组每个元素赋值,要求输出数组中圆柱体半径、高、表面积和体积。
Form类
using System;
using System.Windows.Forms;
namespace Ysa_第三次练习_类与继承
{
public partial class Form1 : Form
{
//实例化圆柱类数组
Cylinder[] cylinders = new Cylinder[3];
//计数器,统计输入的信息个数
int i = 0;
public Form1()
{
InitializeComponent();
}
//每次点击按钮事件,进行一次圆柱体信息的录入
private void button1_Click(object sender, EventArgs e)
{
//接收的信息 圆柱体的半径以及高度
double radius = double.Parse(textBox1.Text);
double hight = double.Parse(textBox2.Text);
//实例化圆柱体,并将参数传入
Cylinder c = new Cylinder(radius,hight);
//将实例化的圆柱体存入数组
cylinders[i] = c;
i++;
//
label1.Text = "初始化第"+(i+1)+"个圆柱体属性";
}
//
private void button2_Click(object sender, EventArgs e)
{
//遍历输出圆柱体数组的信息(借助圆柱体类的方法)
foreach (Cylinder n in cylinders)
{
infor.Text += n.Information() + "\n";
}
}
}
}
Cylinder 圆柱类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ysa_第三次练习_类与继承
{
//圆柱 Cylinder
class Cylinder
{
private double radius;
private double hight;
//参数构造器
public double R
{
get { return radius; }
set
{
if (value > 0)
radius = value;
}
}
public double H {
get { return hight; }
set
{
if (value > 0)
hight = value;
}
}
//求表面积和体积的方法
public double Biaomianji() {
double dmj = radius * radius * Math.PI*2;
double cemianji = hight * 2 * Math.PI * radius;
return dmj + cemianji;
}
public double Tiji() {
return radius*Math.PI*radius*hight;
}
//输出圆柱体的信息
public string Information()
{
string x = "圆柱体的半径:"+radius+"高:"+hight+"表面积:"+Biaomianji()+"体积:"+Tiji();
return x;
}
//构造函数(有参和无参)
public Cylinder() {
}
public Cylinder(double r,double h) {
if (r > 0 && h > 0)
{
radius = r;
hight = h;
}
else
{
throw new ArgumentException("半径必须大于0");
}
}
}
}
删除线
标签:Cylinder,第三次,C#,double,练习,hight,radius,圆柱体,public From: https://www.cnblogs.com/yaolicheng/p/18609618引用
*** 分割线 ---