C#列表隐藏属性?
问题描述:
可能重复:
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'可以找到(你是否缺少使用指令或程序集引用?)
这怎么可能?这是否违反了我们告诉大家的关于不隐藏成员的规则?这里的实现细节是什么?
答
因为实现是通过显式接口实现的。
含义,它的定义为
bool IList<T>.IsReadOnly { get; set; //etc }
http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx
这就是为什么它不是关闭名单。
答
如果你看一下List类,你会看到这一点:
bool IList.IsReadOnly { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
get; }
所有这一切的真正相关的是,IsReadOnly使用明确的执行,这意味着,如果对象是属性只能看到声明宣称为IList。
答
显式接口实现,是这样的:
bool IList<T>.IsReadOnly { get; }
答
List<T>
工具IList<T>
明确的,所以你必须能够访问IsReadOnly
前的对象强制转换为接口。从MSDN:
实现接口的类可以显式实现该接口的成员 。当一个成员被显式实现,它不能被 通过一个类的实例访问,但只能通过 接口实例
要进入细节它能够更好地利用反射的 –