C# List<T> hides properties? [duplicate]
Possible Duplicate:
How does List<T> make IsReadOnly private when IsReadOnly is an interface member?
Okay, this is driving me nuts. List<T>
implements IList<T>
. However,
IList<int> list = new List<i开发者_如何学JAVAnt>();
bool b = list.IsReadOnly;
bool c = ((List<int>)list).IsReadOnly; // Error
The error is:
'System.Collections.Generic.List' does not contain a definition for 'IsReadOnly' and no extension method 'IsReadOnly' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?)
How can this be? Doesn't this violate the very rule that we tell everyone, about not hiding members? What is the implementation detail here?
Because the implementation is via an explicit interface implementation.
Meaning that it's defined as
bool IList<T>.IsReadOnly { get; set; //etc }
http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx
And that is why it's not off of List.
List<T>
implements IList<T>
explicitly so you have to cast the object to the interface before being able to access IsReadOnly
. From MSDN:
A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface
If you look at the List class, you'll see this:
bool IList.IsReadOnly { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
get; }
All that's really relevant is that IsReadOnly is declared using the explicit implementation which means that property can only be seen if the object is declared as that of IList.
Explicit interface implementation, something like:
bool IList<T>.IsReadOnly { get; }
精彩评论