C#中类的继承实例

来源:互联网 发布:win10怎么删除网络2 编辑:程序博客网 时间:2024/04/29 09:15
 

C#中,派生类只能从一个类中继承。这是因为,在C++中,人们在大多数情况下不需要一个从多个类中派生的类。
从多个基类中派生一个类这往往会带来许多问题,从而抵消了这种灵活性带来的优势。
C#中,派生类从它的直接基类中继承成员:方法、域、属性、事件、索引指示器。
除了构造函数和析构函数,派生类隐式地继承了直接基类的所有成员。

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication2{    class Program    {        static void Main(string[] args)        {            Person p1 = new Person();            p1.Name = "所有的人";            p1.Age = 30;            p1.SayHello();            /****************************************/            中国人 c1 = new 中国人();            c1.Name = "中国的人";//继承Person类的属性            c1.Age = 888;//继承Person类的属性            c1.SayHello();//继承Person类的方法            c1.户口 = "中国"; //中国人这个类特有            c1.功夫("降龙十八掌");//中国人这个类特有            /****************************************/            韩国人 k1 = new 韩国人();            k1.Name = "韩国的人";//继承Person类的属性            k1.Age = 80;//继承Person类的属性            k1.SayHello();//继承Person类的方法            k1.泡菜 = "泡菜名";//韩国人这个类特有            k1.偶像剧("小妹叫金三顺");//韩国人这个类特有            /****************************************/            Console.ReadKey();        }    }    class Person    {        public string Name { get; set; }        public int Age { get; set; }        public void SayHello()        {            Console.WriteLine("姓名:{0}  年龄:{1}",this .Name,this.Age  );        }    }    class 中国人 : Person    {        public string 户口 { get; set; }        public void 功夫(string s)        {            Console.WriteLine("中国功夫:{0}",s);        }    }    class 韩国人 : Person    {        public string 泡菜 { get; set; }        public void 偶像剧(string s)        {            Console.WriteLine("电视剧:{0}",s);        }    }}

原创粉丝点击