首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

介面繼承的宣告問題

     編輯:關於C語言

某天,小新問我這樣一個問題:

類別 System.Collections.CollectionBase 是從 IList、ICollection 繼承而來,IList 是從 ICollection 和 IEnumerable 繼承而來,那 CollectionBase 為什麼還要從 ICollection 繼承呢?

我們先看看這些類別和介面在 MSDN 文件中的宣告:

public interface IEnumerable
public interface ICollection : IEnumerable
public interface IList : ICollection, IEnumerable
public abstract class CollectionBase : IList, ICollection, IEnumerable

根據介面繼承規則,CollectionBase 只需宣告實作 IList,就必須同時實作 ICollection,也就必須實作 IEnumerable。那麼,為什麼還要明確把所有介面都寫下來呢?

換句話說,下面兩種宣告沒有實質區別:

// Code #1
public interface IEnumerable
public interface ICollection : IEnumerable
public interface IList : ICollection, IEnumerable
public class ArrayList : IList, ICollection, IEnumerable, ICloneable

// Code #2
public interface IEnumerable
public interface ICollection : IEnumerable
public interface IList : ICollection
public class ArrayList : IList, ICloneable

為何 MSDN 要用第一種?我和小新討論後,一致認為僅為了提高程式碼可讀性。為驗證想法,我分別發郵件給 Eric Gunnerson(C# Compiler Team 成員)和 Kit George(BCL Team 成員)詢問,他們回信如下:

Allen,

I think that readability would be the primary reason people would do this.

Eric

Allen, what you're seeing is simply a doc thing. ArrayList actually only implements IList directly, but we decided in V1.0 of the docs, to highlight the interface hierarchy so you didn't have to wonder 'what does IList implement', you get to see it there on the type.

There is no benefit to ACTUALLY doing this. Try this code, and you'll see it compiles:

using System;
using System.IO;

public class Test : IBob2
{
    void IBob.M() {}
}

interface IBob { void M(); }
interface IBob2 : IBob {}

Regards, Kit

今天查看微軟 Rotor 原始碼,發現 ArrayList 宣告確是 Code #1 做法,但 Mono(ver. 1.1.2)採用 Code #2 做法。

所以,以後若再碰到這種情況,您可以輕鬆一笑:「這樣做是為了提高程式碼可讀性!」

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved