C#中接口的实现

一、继承接口

  声明一个类来实现一个接口,类似一个类从基类派生----实现的接口和基类一起出现在一个以逗号分隔的列表中(谁先谁后无关紧要)。一个类只能从一个基类派生,但是可以实现多个接口

     接口的继承(实现)从逻辑上不与派生类相同,接口的继承相当于表示类遵守接口制定的契约,即必须实现接口中所有的成员,而不是父类子类的继承关系。

     接口永远不能被实例化,并且不能包含static成员。

    接口显示成员实现:

 1 // <copyright file="IListable.cs" company="TNT">
 2 // Copyright (c) TNT. All rights reserved.
 3 // </copyright>
 4 // <author>Li Mingjian</author>
 5 // <date> 2014-11-16 </date>
 6 // <summary>显示一行数据的接口</summary>
 7 namespace InterfaceExplicit
 8 {
 9     using System;
10     using System.Collections.Generic;
11     using System.Linq;
12     using System.Text;
13 
14     /// <summary>
15     /// A interface of show a row data
16     /// </summary>
17     /// <see cref=""></see>
18     /// <remarks>
19     /// <c>创建人:Li 
20     /// 创建日期:2014-11-16
21     /// 版本:1.0</c>
22     /// </remarks>
23     interface IListable
24     {
25         // 返回一行中的每一列数据
26         string[] Columnvalues
27         {
28             get;
29         }
30     }
31 }
View Code

在Conact类中实现他,注意是显式实现

 1 // <copyright file="Contact.cs" company="TNT">
 2 // Copyright (c) TNT. All rights reserved Contact.cs.
 3 // </copyright>
 4 // <author>Li Mingjian</author>
 5 // <date> 2014-11-16 </date>
 6 // <summary>联系人抽象类</summary>
 7 namespace InterfaceExplicit
 8 {
 9     using System;
10     using System.Collections.Generic;
11     using System.Linq;
12     using System.Text;
13 
14     /// <summary>
15     /// A Contact class with set and show member information
16     /// </summary>
17     /// <see cref=""></see>
18     /// <remarks>
19     /// <c>创建人:Li 
20     /// 创建日期:2014-11-16
21     /// 版本:1.0</c>
22     /// </remarks>
23     internal class Contact : IListable, IComparable
24     {
25         #region ILitable Members
26         /// <summary>
27         /// Gets information of member
28         /// </summary>
29         string[] IListable.Columnvalues
30         {
31             get
32             {
33                 return new string[]
34                 {
35                     FirstName,
36                     LastName,
37                     Phone,
38                     Address
39                 };
40             } // get
41         } // Columvalues
42         #endregion
43 
44         /// <summary>
45         /// Realize CompareTo
46         /// </summary>
47         /// <param name="obj"> The obj to be compared with this</param>
48         /// <returns></returns>
49         public int CompareTo(object obj)
50         {
51             //...
52         } // CompareTo
53     } // class
54 } // namespace InterfaceExplicit
View Code

下面演示如何调用显式实现的。调用显式实现的接口成员时,必须将类转型为接口才可以调用,这点与隐式不同。

 value = ((IListable)contact).Columnvalues;

至于隐式实现很普遍,上一篇博客里涉及到的就是隐式实现。

转型看上去只是语法上的区别,实际上这从设计的角度已经不同了。

显式接口实现是将“机制方面的考虑”与“模型方面的考虑”分开的一种技术。例如Contact本属于联系人的类,不可以比较,但是他实现了可比较的接口,所以转型后,可以认为他拥有了可比较的机制,但是“模型”层面Contact还是不可比较的。

可以显式的区分你想什么时候与模型打交道,什么时候与机制沟通。

posted @ 2014-11-16 11:22  TNT-boom  阅读(338)  评论(0)    收藏  举报