C#繼承機制 多級繼承

來源:互聯網
上載者:User

標籤:

一些物件導向語言允許一個類從多個基類中繼承,而另一些物件導向語言只允許從一個類繼承,但可以隨意從幾個介面或純抽象類別中繼承。

只有C++支援多級繼承,許多程式員對此褒貶不一。多級繼承常會引起繼承來的類之間的混亂,繼承而來的方法往往沒有唯一性,所以C#中類的繼承只可以是一個,即子類只能派生於一個父類,而有時你必須繼承多個類的特性,為了實現多重繼承必須使用介面技術,下面是對介面的多重繼承進行介紹:
  
using System ;
//定義一個描述點的介面
interface IPoint
{
int x {
get ;
set ;
}
int y {
get ;
set ;
}
}
interface IPoint2
{
int y {
get ;
set ;
}
}
//在point中繼承了兩個父類介面,並分別使用了兩個父類介面的方法 
class Point:IPoint,IPoint2
{
//定義兩個類內部訪問的私人成員變數
private int pX ;
private int pY ;
public Point(int x,int y) {
pX=x ;
pY=y ;
}
//定義的屬性,IPoint介面方法實現
public int x
{
get
{ return pX ; }
set
{ pX =value ; }

//IPoint1介面方法實現 
public int y
{
get
{ return pY ; }
set
{ pY =value ; }
}
}
class Test
{
private static void OutPut( IPoint p )
{ Console.WriteLine("x={0},y={1}",p.x,p.y) ; }
public static void Main( ) {
Point p =new Point(15,30) ;
Console.Write("The New Point is:") ;
OutPut( p ) ;
string myName =Console.ReadLine( ) ;
Console.Write("my name is {0}", myName) ;
}
}  

  

C#繼承機制 多級繼承

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.