C#学习(四)

本周主要讲了C#中接口的使用方法,包括如何定义和实现接口、继承多个接口、扩展接口、组合接口、接口的多态、接口与抽象类的对比等等。

1. 接口的作用、使用接口的好处

  接口其实就是类和类之间的一种协定,一种约束。定义接口,里面包含方法,但没有方法具体实现的代码,然后在继承该接口的类里面要实现接口的所有方法的代码。当类继承于一个接口时,这就方便了类的定义(不会忘记定义某个方法,因为必须实现接口的所有方法)和使用(在接口中的方法在类中肯定都有实现)。

2. 定义和实现接口定义接口的代码如下:

1 [attributes] [access-modifiers] interface interface-name [:base-inteface-list] 
2 { 
3     interface body 
4 }
[attributes]:性质:可选项、可有多个性质;
[access-modifiers]:访问修饰符:可选项。可有多个性质public, internal, private, protected, protected internal; Default: internal;
interface:关键字;
interface-name:接口名,一般以I开头;
[:base-inteface-list]:接口基类列表:可选项、可有多个;
interface body:接口主体(不能有访问修饰符):只是定义接口的方法和属性等的签名、实际的实现是写在使用该接口的class里。

定义和实现接口实例如下:
 1 public interface IStorable
 2 {
 3     void Read( );
 4     void Write(object);
 5 }
 6 
 7 public class Document : IStorable
 8 {
 9     public void Read( ) {    //定义内容   }
10     public void Write(object obj) {        //定义内容    }
11 }

3. 类可继承多个接口,且必须实现接口的所有方法

 1 public interface IStorable
 2 {
 3     void Read( );
 4     void Write(object);
 5 }
 6 
 7 interface ICompressible
 8 {
 9     void Compress();
10     void Decompress();
11 }
12 
13 public class Document : IStorable, ICompressible 
14 {
15     //实现IStorable
16     public void Read( ) {...}
17     public void Write(object obj) {...}
18     // 实现ICompressible
19     public void Compress(){ …}
20     public void Decompress() { …}
21 }

4. 扩展接口:可以通过加入方法或者属性来扩展一个借口,相当于接口的子接口

 1 interface ICompressible
 2 {
 3     void Compress();
 4     void Decompress();
 5 }
 6 
 7 interface ILoggedCompressible : ICompressible
 8 {
 9     void LogSavedBytes();
10 }
11 
12 public class Document : ILoggedCompressible 
13 {
14     // 实现ICompressible
15     public void Compress(){ ...}
16     public void Decompress() { ...}
17     // 实现ILoggedCompressible 
18     public void LogSavedBytes() { ...}
19 }

5. 组合接口,由于一个接口可以继承多个父接口,所以可以定义一个继承于多个父接口的子接口,来实现两个接口的组合

interface IStorableCompressible : IStorable, ILoggedCompressible
{
    void LogOriginalSize();  //增加的新方法
}

6. 其他

  (1)同样的,接口也可以实现多态;

  (2)as 运算符:将左操作数转换成右操作数类型( IStorable isDoc = doc as IStorable; ),如果转换不成功则返回null;

  (3)接口与抽象类的区别在于,抽象类更侧重于"继承"上的一脉相承,接口则只看重"功能"上的一致性,不关心"血脉"关系;

  

 总之接口的功能十分丰富,熟练使用接口能增加编程工作的效率。


原文地址:https://www.cnblogs.com/yongheng20/p/4396358.html