How does ReadOnlyCollection hide Add and Remove methods
ReadOnlyCollection<T>
realises the ICollection<T>
interface which has methods like Add and Remove. I know how to hide methods from Intellisense using attributes, but how is it possible to cause an actual compilation error if I try to use these methods?
(Btw, I know it开发者_运维问答 doesn't make sense to call Add and Remove on a ROC, it's a question on causing compilation error for inherited memebers, not on using the correct data structure).
They're implemented with explicit interface implementation, like this:
void ICollection<T>.Add(T item) {
throw NotSupportedException();
}
The method is still callable, but only if you view the object as an ICollection<T>
. For example:
ReadOnlyCollection<int> roc = new ReadOnlyCollection<int>(new[] { 1, 2, 3 });
// Invalid
// roc.Add(10);
ICollection<int> collection = roc;
collection.Add(10); // Valid at compile time, but will throw an exception
Indeed, by implementing those methods from the ICollection<T>
interface explicitly, you cannot call them directly.
You'll have to cast the object (the ReadOnlyCollection
instance) to ICollection<T>
explicitly. Then, you can call the Add method. (Hence, the compiler won't complain, although you'll get a runtime exception).
精彩评论