C#继承初学

来源:互联网 发布:怎么做好软件测试 编辑:程序博客网 时间:2024/06/14 23:25


在我的理解范围内,继承就是将被继承类的成员分享给继承类。所以自然而然,protected定义的函数、变量等等就都可以进行访问,这也是对于一些值安全性的考虑:这些值、函数出于安全性考虑并不想被所有类可修改,所以定义为protected型,当有类继承该类后继承类才可对这些数据进行改动。

实践编辑代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication2{    class Program    {        protected int Width, Length;        public void setWidth(int w)        {            Width = w;        }        public void setLength(int l)        {            Length = l;        }            }    class Run    {        static void Main(string[] args)        {            Pro rec = new Pro();//开始时忘记类的声明了            rec.setLength(3);            rec.setWidth(4);            int a = rec.area();            Console.WriteLine("The area of the rectangle is {0}。\n", a);            Console.ReadKey();            //Console.WriteLine("The width of the rectangle is {0}", rec.Width);            Console.ReadKey();        }    }    class Pro : Program    {        public int area()        {            int Area;            Console.WriteLine("The width is {0}\n", Width);            Area = Width * Length;            return Area;        }    }}

其实很明显可以看出,继承类有点类似与被继承类的衍生,或者说是其中的一部分.


关于多重继承的类似形式,由于应该用不到,所以不进行实践了,使用到的话再去查找interface相关使用。


原创粉丝点击