深入剖析C#继承机制5

类别:.NET开发 点击:0 评论:0 推荐:
四、多级继承

  一些面向对象语言允许一个类从多个基类中继承,而另一些面向对象语言只允许从一个类继承,但可以随意从几个接口或纯抽象类中继承。

  只有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) ;
}
}

本文地址:http://com.8s8s.com/it/it42471.htm