通过类继承计算梯形面积

Posted on 2018-12-06 01:17  努力成长静待花开  阅读(356)  评论(0编辑  收藏  举报

实现效果:

  

 知识运用:

  c#中实现继承的语法格式:Class DerivedClass:BaseClass{ }

  继承类时 ,必须在子类和基类之间使用冒号(:)

实现代码:

        private void button1_Click(object sender, EventArgs e)
        {
            double argU, argD, argH;
            bool safe=double.TryParse(textBox1.Text,out argU)&
                    double.TryParse(textBox2.Text,out argD)&
                    double.TryParse(textBox3.Text,out argH);
            if (safe)
            {
                trapeziaArea tar = new trapeziaArea();
                tar.SD = argU;
                tar.XD = argD;
                tar.HEIGHT = argH;
                label1.Text = ("面积: " + tar.area().ToString());
            }
            else { MessageBox.Show("请输入正确的数字"); }
        }
        class trapezia {
            private double sd;
            private double xd;
            private double height;
            public double SD { get { return sd; } set { if (value > 0)sd = value; } }
            public double XD { get { return xd; } set { if (value > 0)xd = value; } }
            public double HEIGHT { get { return height; } set { if (value > 0)height = value; } }
        }
        class trapeziaArea:trapezia
        {
            public double area() {
                return (SD + XD) * HEIGHT / 2;
            }
        }