看接口System.Collections.Generic.ICollection其定义要求继承成员包含属性bool IsReadOnly {get; }。列表和集合
但是我当时看了一下类System.Collections.Generic.List它继承了System.Collections.Generic.ICollection这个类不包含BOOL IsReadOnly的定义{获得; }。继承链如何被打破或者我错过了什么?
看接口System.Collections.Generic.ICollection其定义要求继承成员包含属性bool IsReadOnly {get; }。列表和集合
但是我当时看了一下类System.Collections.Generic.List它继承了System.Collections.Generic.ICollection这个类不包含BOOL IsReadOnly的定义{获得; }。继承链如何被打破或者我错过了什么?
IsReadOnly
属性是那里,但是List<T>
正在执行它explicitly。
说服这个自己,你可以这样做:
List<T> genericList = new List<T>();
IList explicitIList = genericList;
bool isReadOnly = explicitIList.IsReadOnly;
这应该编译。
你可能也想看看这个question和这个article关于如何明确地实现接口,以及如何引用一个明确实现的成员在类型之外的类型。
它是在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
}
是。它是明确实施的。所以你应该以这种方式访问它的成员(明确地将其转换为接口) ((ICollection)list).IsReadOnly;
从System.Collections.Generic.List的.NET反射器中的反汇编代码,它确实包含IsReadOnly
属性。
bool ICollection<T>.IsReadOnly { get; }