如何让一个支持IList的类的this[int index].get的返回类型为某一固定类型(而非object)?

cat_hsfz 2005-07-12 08:02:23
今天模仿着做一个IList类,是用Reflector看着System.Web.UI.WebControls.ListItemCollection做的。IList要求实现object this[int index]{get;set;},然而我看到ListItemCollection是通过如下方法实现固定返回类型的:(这是Reflector提供的C#代码)
void IList.set_Item(int index, object value)
{
this.listItems[index] = (ListItem) value;
}

public ListItem this[int index]
{
get
{
return (ListItem) this.listItems[index];
}
}

然而我模仿着这样去做,却无法通过编译,为什么呢?难道.NET Framework使用的编译器比我们的要宽松,甚至它直接写IL的?
...全文
175 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
cat_hsfz 2005-07-13
  • 打赏
  • 举报
回复
可以通过编译了,谢谢!

不过我还是不懂为什么能够这样做,请问能否详细解释一下?
cat_hsfz 2005-07-13
  • 打赏
  • 举报
回复
那为什么public ListItem this[int index]就能够隐藏掉上面的object IList.this[int index].get?

另外为什么那么多.NET Framework里面实现IList的类不直接从CollectionBase继承,而是自己重写所有的接口?
linfengcyl 2005-07-13
  • 打赏
  • 举报
回复
接口显式实现啊.也可以从CollectionBase继承
psn 2005-07-12
  • 打赏
  • 举报
回复
object IList.this[int index]
{
get
{
return this[index]
}
}

public ListItem this[int index]
{
}
psn 2005-07-12
  • 打赏
  • 举报
回复
1.C#中this属性默认是Item属性,编译成get_Item和set_Item方法。你可以添加DefaultMemberAttribute改变this映射到其它属性。
2.返回值重载可以用显示接口实现的技巧实现。
object IList.this[int index]
{
get

}

public ListItem this[int index]
{
}

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧