2011-09-23 72 views
1

可能重复:
How does List<T> make IsReadOnly private when IsReadOnly is an interface member?C#列表<T>隐藏属性?

好了,这是推动我坚果。 List<T>执行IList<T>。然而,

IList<int> list = new List<int>(); 
bool b = list.IsReadOnly; 
bool c = ((List<int>)list).IsReadOnly; // Error 

错误是:

“System.Collections.Generic.List”不包含关于“IsReadOnly”和没有扩展方法的定义“IsReadOnly”接受类型的第一个参数'System.Collections.Generic.List'可以找到(你是否缺少使用指令或程序集引用?)

这怎么可能?这是否违反了我们告诉大家的关于不隐藏成员的规则?这里的实现细节是什么?

+0

要进入细节它能够更好地利用反射的 –

回答

0

如果你看一下List类,你会看到这一点:

bool IList.IsReadOnly { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] 
     get; } 

所有这一切的真正相关的是,IsReadOnly使用明确的执行,这意味着,如果对象是属性只能看到声明宣称为IList。

0

显式接口实现,是这样的:

bool IList<T>.IsReadOnly { get; } 
1

List<T>工具IList<T>明确的,所以你必须能够访问IsReadOnly前的对象强制转换为接口。从MSDN:

实现接口的类可以显式实现该接口的成员 。当一个成员被显式实现,它不能被 通过一个类的实例访问,但只能通过 接口实例