2010-08-19 58 views
0

看接口System.Collections.Generic.ICollection其定義要求繼承成員包含屬性bool IsReadOnly {get; }列表和集合

但是我當時看了一下類System.Collections.Generic.List它繼承了System.Collections.Generic.ICollection這個類不包含BOOL IsReadOnly的定義{獲得; }。繼承鏈如何被打破或者我錯過了什麼?

回答

1

IsReadOnly屬性那裏,但是List<T>正在執行它explicitly

說服這個自己,你可以這樣做:

List<T> genericList = new List<T>(); 
IList explicitIList = genericList; 

bool isReadOnly = explicitIList.IsReadOnly; 

這應該編譯。

你可能也想看看這個question和這個article關於如何明確地實現接口,以及如何引用一個明確實現的成員在類型之外的類型。

1

它是在IList的部分:

的IList實現ICollection的

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable 
    { 
     public List(); 
     public List(int capacity); 
     public List(IEnumerable<T> collection); 
     public int Capacity { get; set; } 

     #region IList Members 

     int IList.Add(object item); 
     bool IList.Contains(object item); 
     void ICollection.CopyTo(Array array, int arrayIndex); 
     int IList.IndexOf(object item); 
     void IList.Insert(int index, object item); 
     void IList.Remove(object item); 
     bool IList.IsFixedSize { get; } 
     bool IList.IsReadOnly { get; } 
     bool ICollection.IsSynchronized { get; } 
     object ICollection.SyncRoot { get; } 
     object IList.this[int index] { get; set; } 

     #endregion 

...and so on 

} 
0

是。它是明確實施的。所以你應該以這種方式訪問​​它的成員(明確地將其轉換爲接口) ((ICollection)list).IsReadOnly;

0

從System.Collections.Generic.List的.NET反射器中的反彙編代碼,它確實包含IsReadOnly屬性。

bool ICollection<T>.IsReadOnly { get; }