CLR Via C# 3rd 阅读摘要 -- Chapter 13 - Interfaces

Class and Interface Inheritance

1. C#不允许class的多重继承,而interface可以多重继承;

2. interface的继承不同于类继承, interface的继承只是规约的继承,而没有包含任何实现。

Defining an Interface

1. interface除了方法外,还可以定义事件、无参属性、有参属性(C#:indexer),因为这些归根结底还是方法;

2. 虽然CLR允许interface定义静态方法、静态字段、常量、静态构造器。但是CLI兼容的interface应该避免,而且C#阻止定义这些静态成员;

3. interface一般约定以I作为前缀;

4. CLR支持泛型interface。

Inheriting an Interface

1. interface定义的方法就是public的,CLR要求interface的方法是virtual的。

2. interface中的方法如果没有显式的指定virtual,那么编译器给该方法加上virtual + sealed,如果显式指定virtual,那么编译器给该方法标上virtual,但是unsealed。

More About Calling Interface Methods

1. 值类型也可以像引用类型一样实现interface,但是在转换一个值类型的实例到接口时需要装箱操作。

Implicit and Explicit Interface Method Implementations

1. EIMI: Explicit Interface Method Implementation;

2. EIMI方法不能标记为virtual因此不能被覆盖,因为EIMI方法实际上不适对象模型的一部分。 

Generic Interfaces

1. 泛型接口可以提供编译时类型安全;

2. 在使用值类型时,泛型接口可以避免装箱操作;

3. interface的泛型类型参数可以标记为逆变(contravariant)和协变(covariant)。 

Generics and Interface Constraints

1. private static Int32 M<T t> where T : IComparable, IConvertible {...};

2. 在一个值类型上调用接口方法总是引发装箱操作。

Implementing Multiple Interfaces That Have the Same Method Name and Signature

1. By EIMI。

Improving Compile-Time Type Safety with Explicit Interface Method Implementations

1. EIMI经常用在需要实现IConvertible, ICollection, IList, IDictionary这样的接口时。

Be Careful with Explicit Interface Method Implementations

1. 没有文档解释一个类型特定的实现了一个EIMI方法,VS的IntelliSense也不支持;

2. 值类型的实例在转换到接口时有装箱;

3. EIMI不能被子类调用。

Design:Base Class or Interface?

1. Guidelines:

  • 正确区别IS-A vs CAN-DO关系;
  • 怎么样使用起来简单,别滥用接口; 
  • 实现的一致性,提供一个基类是一个好的默认实现,可以快速开始;
  • 版本问题,在interface中加入成员会要求重新编译。 

2. 建议的方法:定义接口,并提供一个基类(通常是抽象的)来实现该接口。 

本章小结

  本章讲述了interface和class之间的区别,示范了如何定义一个接口以及接口的继承, 解释了在调用接口时CLR的行为,说明了隐式接口实现与显示接口实现(EIMI)的区别,着重说明EIMI的用途。然后讲了如何定义泛型接口,使用泛型接口的好处,如何对泛型接口的泛型类型参数进行约束(逆变out与协变in)。还讲了如何实现不同接口的多个同名同签名的方法(使用EIMI支持)。最后对接口和基类的设计抉择给出了指导性建议。

 

posted @ 2010-04-12 15:07  bengxia  阅读(265)  评论(0编辑  收藏  举报
无觅相关文章插件,快速提升流量