【问题标题】:How does ReadOnlyCollection hide Add and Remove methodsReadOnlyCollection 如何隐藏 Add 和 Remove 方法
【发布时间】:2010-11-08 07:54:23
【问题描述】:
ReadOnlyCollection<T> 实现了ICollection<T> 接口,该接口具有 Add 和 Remove 等方法。我知道如何使用属性从 Intellisense 中隐藏方法,但是如果我尝试使用这些方法,怎么可能导致实际的编译错误?
(顺便说一句,我知道在 ROC 上调用 Add 和 Remove 是没有意义的,这是一个导致继承成员编译错误的问题,而不是使用正确的数据结构)。
【问题讨论】:
标签:
c#
interface
readonly-collection
【解决方案1】:
它们是用explicit interface implementation 实现的,像这样:
void ICollection<T>.Add(T item) {
throw NotSupportedException();
}
该方法仍然可以调用,但前提是您将对象视为ICollection<T>。例如:
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
【解决方案2】:
确实,通过显式地从ICollection<T> 接口实现这些方法,您无法直接调用它们。
您必须将对象(ReadOnlyCollection 实例)显式转换为 ICollection<T>。然后,您可以调用 Add 方法。 (因此,编译器不会抱怨,尽管你会得到一个运行时异常)。