C# 通过接口实现多重继承

  • Post author:
  • Post category:其他


using System;
using System.Collections.Generic;
using System.Text;
//通过接口实现多重继承
namespace interfaceDemo
{
    class Person {//定义实体类
        internal int age;
        internal string name;
        bool isMale;
        public Person(int age, string name, bool isMale) {//构造方法

            this.age = age;
            this.name = name;
            this.isMale = isMale;
        }
        public bool IsMale() {

            return this.isMale;
        }
    }

    interface Teacher//定义接口
    {
        string GetSchool();//接口里的方法都是抽象的
        string GetSubject();

    }
    interface Doctor
    {
        string GetHospital();
        double GetSalary();
    }

    class PersonA : Person, Teacher//继承person类、实现Teacher接口
    {

        public PersonA(int age, string name, bool isMale)
            : base(age, name, isMale)//派生类调用积累的构造方法
        { 
          
        
        }
        public string GetSchool()//实现接口的抽象方法
        {
            return "清华大学";
        }
        public string GetSubject()//实现接口的抽象方法
        {
            return "经济学";
        }


    }

    class PersonB : Person, Teacher, Doctor//继承person类,同时实现两个接口
    {

        public PersonB(int age, string name, bool isMale)
            : base(age, name, isMale)
        { 
        
        }
        public string GetSchool()
        {
            return "北京大学";
        }
        public string GetSubject()//实现接口的抽象方法
        {
            return "计算机";
        }
        public string GetHospital() {

            return "北京附属医院";
        }
        public double GetSalary() {

            return 2000;
        }

    }
    class TestInterface//测试类
    {
        static void Main(string[] args) {

            PersonA p1 = new PersonA(40, "张三", true);
            string gender = "";
            if (p1.IsMale())
            {
                gender = "男";
            }
            else {
                gender = "女";
            }
            Console.WriteLine("{0},{1},{2}岁,{3}教师,专业是{4}", p1.name, gender, p1.age, 
                p1.GetSchool(), p1.GetSubject());//调用接口已经实现的方法

            PersonB p2 = new PersonB(55, "赵六", false);
           
            if (p2.IsMale())
            {
                gender = "男";
            }
            else
            {
                gender = "女";
            }
            Console.WriteLine("{0},{1},{2}岁,{3}教师,专业是{4},\n同时也是{5}医生,工资为{6}", 
                p2.name, gender, p2.age, p2.GetSchool(), p2.GetSubject(),p2.GetHospital(),p2.GetSalary());
            Console.ReadLine();
        
        }
    }
}



版权声明:本文为iteye_12996原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。