ホームページ  >  記事  >  バックエンド開発  >  C#学習日記22---多重継承

C#学習日記22---多重継承

黄舟
黄舟オリジナル
2017-01-21 15:23:411566ブラウズ

継承は、オブジェクト指向プログラミングで最も重要な概念の 1 つです。継承により、あるクラスに基づいて別のクラスを定義することができます。クラスが別のクラスから派生する場合、派生クラスは基本クラスからの特性を継承します (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("狗", "汪汪");  
        }  
    }  
}

結果 re 多重継承: 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 中国語 Web サイト (www.php.cn) にアクセスしてください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。