Visual Studio 2010——C#中的类

来源:互联网 发布:电子阅览室软件破解 编辑:程序博客网 时间:2024/06/05 10:06

实验环境:Windows XP,Visual Studio 2010  Ultimate


1 创建项目:

       文件>>新建>>项目,选中“控制台应用程序”。如下图所示:


2 添加以下代码:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace testClassApp{    //抽象基类,不可实例化    abstract class Shape     {        public const double pi = 3.14; //常量        protected double x, y; //保护,可继承变量                //无参构造函数        public Shape()        {            x = y = 0;        }        //带参构造函数        public Shape(double x, double y)        {            this.x = x;            this.y = y;        }        //抽象函数,必须重载        public abstract double Area();    }    //子类——继承抽象类Shape    class Rectangle : Shape    {        //base(),使用基类函数        public Rectangle() : base() { }        public Rectangle(double x, double y) : base(x, y) { }                //重载基类抽象函数        public override double Area()        {                return(x*y);        }        //属性:矩形长度        public double length        {             get             {                 return x;             }            set            {                 if(value>0)                 {                     x = value;                  }            }        }        //属性:矩形宽度        public double width        {            get            {                return y;            }            set            {                if(value>0)                {                    y = value;                }            }        }    }    //子类——继承抽象类Shape    class Ellipse:Shape    {        //使用基类构造函数        public Ellipse(double x, double y):base(x, y){}        //重载虚函数        public override double  Area()        {         return pi*x*y;        }    }    //孙类——继承Ellipse    class Circle:Ellipse    {        //使用基类构造函数        public Circle(double r):base(r,0){}        //重载Area函数。注:Area()已经不是虚函数        public override double  Area()        {         return pi*x*x;        }    }    //入口类    class Program    {        static void Main(string[] args)        {            double len = 2.5;            double wid = 3.0;            double rad = 4.1;            Rectangle aRect = new Rectangle();            //使用其属性            aRect.length = len;            aRect.width = wid;            Circle aCirc = new Circle(rad);            Console.WriteLine("Area of Rect is:{0}",aRect.Area());            Console.WriteLine("Area of Circ is:{0}",aCirc.Area());        }    }}

3 调试:

       调试>>启动调试,结果如下


4 工程源码。点击这里下载。 


参考资料

《C#实用编程百例》,清华大学出版社,何鹏飞,王征等编著

原创粉丝点击