首頁  >  文章  >  後端開發  >  C#學習日記22---多重繼承

C#學習日記22---多重繼承

黄舟
黄舟原創
2017-01-21 15:23:411566瀏覽

   繼承是物件導向程式設計中最重要的概念之一。繼承允許我們根據一個類別來定義另一個類別來定義一個類別,一個類別從另一個類別派生出來時,衍生類別從基底類別那裡繼承特性

         繼承的思想實現了 屬於(IS-A) 關係關係。例如,哺乳動物 屬於(IS-A) 動物,狗屬於(IS-A) 哺乳動物,因此狗 屬於(IS-A) 動物。

基類與派生類別:

    C#中派生類別從他的直接基類繼承成員,方法、屬性、域、事件、索引指示器但是除開構造函數與析構函數。

 下面寫個實例。 

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    class Anlimal  //定义一个基类  
    {  
        protected int foot = 4;  
        protected double weight = 22.4;  
        protected void say(string type, string call)  
        {  
            Console.WriteLine("类别:{0},叫声:{1} ",type,call);  
        }  
    }  
   
    //Dog 继承Anlimal   
    class Dog:Anlimal  
    {  
        static void Main(string[] args)  
        {  
            Dog dog = new Dog();  
            int foot = dog.foot;  
            double weight = dog.weight;  
            Console.WriteLine("dog foot: {0}\ndog weight:{1}",foot,weight);  
            dog.say("狗", "汪汪");  
        }  
    }  
}

結果

C#學習日記22---多重繼承

多重繼承:

         C# 不支援多重繼承。但是,您可以使用介面來實現多重繼承,上面的例子我們為他添加一個smallanlimal介面

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace Test  
{  
    class Anlimal  //定义一个基类  
    {  
        protected int foot = 4;  
        protected double weight = 22.4;  
        protected void say(string type, string call)  
        {  
            Console.WriteLine("类别:{0},叫声:{1} ",type,call);  
        }  
    }  
  
    public interface smallanlimal  //添加一个接口 接口只声明方法在子类中实现  
    {  
        protected void hight(double hight);  
         
    }  
    //Dog 继承Anlimal   
    class Dog:Anlimal,smallanlimal  
    {  
        public void hight(double hight)  //实现接口  
        {  
            Console.WriteLine("Hight: {0}",hight);  
        }  
        static void Main(string[] args)  
        {  
            Dog dog = new Dog();  
            int foot = dog.foot;  
            double weight = dog.weight;  
            dog.hight(23.23);  
            Console.WriteLine("dog foot: {0}\ndog weight:{1}",foot,weight);  
            dog.say("狗", "汪汪");  
        }  
    }  
}

以上就是 C#學習日記22---多重繼承的內容,更多相關內容請關注PHP中文網(www. php.cn)!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn