C#接口和JAVA的区别?

接口是一种“主干类”,包含方法签名但是没有方法的实现。在这个方面,接口与抽象类一样,只包含抽象方法。C# 接口非常类似于 Java 接口,工作原理基本一样。

接口的所有成员都定义为公共成员,并且接口不能包含常量、字段(私有数据成员)、构造函数、析构函数或任何类型的静态成员。如果为接口的成员指定任何修饰符,编译器将会产生错误。

为了实现接口,我们可以从接口派生类。这样的派生类必须为所有接口的方法提供实现,除非派生类声明为抽象的。

接口的声明与 Java 完全一样。在接口定义中,通过单独使用 get 和 set 关键字,属性仅指示它的类型,以及它是只读的、只写的还是可读写的。下面的接口声明了一个只读属性:

 1 None.gif public   interface  IMethodInterface
 2 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 3InBlock.gif  // method signatures
 4InBlock.gif  void MethodA();
 5InBlock.gif  int MethodB(float parameter1, bool parameter2);
 6InBlock.gif
 7InBlock.gif  // properties
 8InBlock.gif  int ReadOnlyProperty
 9ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
10InBlock.gif    get;
11ExpandedSubBlockEnd.gif  }

12ExpandedBlockEnd.gif}

13 None.gif
14 None.gif

用一个冒号来代替 Java 的实现关键字,类就可以继承此接口。实现类必须提供所有方法的定义以及任何必需的属性访问器:

 1 None.gif public   class  InterfaceImplementation : IMethodInterface
 2 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 3InBlock.gif  // fields
 4InBlock.gif  private int count = 0;
 5InBlock.gif  private int ID;
 6InBlock.gif
 7InBlock.gif  // implement methods defined in interface
 8InBlock.gif  public void MethodA()
 9ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
10InBlock.gif    dot.gif
11ExpandedSubBlockEnd.gif  }

12InBlock.gif
13InBlock.gif  public int MethodB(float parameter1, bool parameter2)
14ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
15InBlock.gif    dot.gif
16InBlock.gif    return integerVariable;
17ExpandedSubBlockEnd.gif  }

18InBlock.gif
19InBlock.gif  public int ReadOnlyProperty
20ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
21InBlock.gif    get
22ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
23InBlock.gif      return count;
24ExpandedSubBlockEnd.gif    }

25ExpandedSubBlockEnd.gif  }

26InBlock.gif
27InBlock.gif  // add extra methods if required
28InBlock.gif
29ExpandedBlockEnd.gif}

30 None.gif
31 None.gif

实现多个接口

通过使用下面的语法,一个类可以实现多个接口:

None.gif public   class  MyClass : interfacename1, interfacename2, interfacename3

如果一个类实现多个接口,则成员的名称会存在二义性,通过使用属性或方法名的完全限定符可以解决这个问题。换句话说,通过使用方法的完全限定名来指示它属于哪个接口(例如属于 IMethodInterface.MethodA),派生类可以解决这种冲突。

文章来自: http://www.microsoft.com/china/msdn/library/langtool/vcsharp/Usgettingstartedcsharpforjava.mspx?mfr=true

转载于:https://www.cnblogs.com/support/archive/2006/09/29/518729.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值