C#列表<;T>;隐藏属性?

C#列表<;T>;隐藏属性?,c#,member-hiding,C#,Member Hiding,可能重复: 好吧,这让我快发疯了列表实现IList。但是, IList<int> list = new List<int>(); bool b = list.IsReadOnly; bool c = ((List<int>)list).IsReadOnly; // Error IList list=new list(); bool b=list.IsReadOnly; bool c=((列表)列表).IsReadOnly;//错误 错误是: “Sy

可能重复:

好吧,这让我快发疯了<代码>列表实现
IList
。但是,

IList<int> list = new List<int>();
bool b = list.IsReadOnly;
bool c = ((List<int>)list).IsReadOnly;    // Error
IList list=new list();
bool b=list.IsReadOnly;
bool c=((列表)列表).IsReadOnly;//错误
错误是:

“System.Collections.Generic.List”不包含“IsReadOnly”的定义,并且找不到接受“System.Collections.Generic.List”类型的第一个参数的扩展方法“IsReadOnly”(是否缺少using指令或程序集引用?)


这怎么可能?这是否违反了我们告诉所有人不要隐藏成员的规则?这里的实现细节是什么?

因为实现是通过显式接口实现的

意思是它被定义为

bool IList<T>.IsReadOnly { get; set; //etc }
bool-IList.IsReadOnly{get;set;//etc}


这就是为什么它没有被排除在名单之外

因为实现是通过显式接口实现的

意思是它被定义为

bool IList<T>.IsReadOnly { get; set; //etc }
bool-IList.IsReadOnly{get;set;//etc}


这就是为什么它没有被排除在名单之外

如果查看List类,您将看到:

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

真正相关的是IsReadOnly是使用显式实现声明的,这意味着只有当对象声明为IList的对象时才能看到属性。

如果查看List类,您会看到:

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

真正相关的是IsReadOnly是使用显式实现声明的,这意味着只有当对象声明为IList的对象时,才能看到属性。

显式接口实现,类似于:

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

显式接口实现,类似于:

bool IList<T>.IsReadOnly { get; }
bool-IList.IsReadOnly{get;}
列表
显式实现了
IList
,因此您必须将对象强制转换到接口才能访问
IsReadOnly
。从MSDN:

实现接口的类可以显式实现成员 这个界面的一部分。当成员显式实现时,它不能 可以通过类实例访问,但只能通过 接口

List
显式实现了
IList
,因此您必须将对象强制转换到接口才能访问
IsReadOnly
。从MSDN:

实现接口的类可以显式实现成员 这个界面的一部分。当成员显式实现时,它不能 可以通过类实例访问,但只能通过 接口


如:(1)深入了解细节更好地利用反射器;(2)深入了解细节更好地利用反射器