ASP.Net 2.0 中的List的问题。

zahuifan 2006-08-23 11:43:40
以前,我用VS2003的时候,可以使用ArrayList.ReadOnly()函数:
public class A {
private ArrayList _students = new ArrayList();

pubic ArrayList students {
get { return ArrayList.ReadOnly(_students);
}
}

使用ArrayList.ReadOnly()函数可以防止Client是使用 new A().students.Add()方法.

现在我使用VS2005的List<T>:
public class A {
private IList<Student> _students = new List<Students>();

public IList<Student> students {
get { return ? }
}
}

发现List<T>并没有ReadOnly()函数.那么我怎么才能返回一个不允许添加项目的List<T>呢?

ps: 后来发现System.Collections.ObjectModel命名空间有一个ReadOnlyCollection<T>类, 可以
return new System.Collections.ObjectModel.ReadOnlyCollection<string>(_students);

不知道还有没有更好的方法?

还有我是应该写成:
public ICollection<Student> students {
get { return new System.Collections.ObjectModel.ReadOnlyCollection<string>(_students); }
}

还是

public IList<Student> students {
get { return new System.Collections.ObjectModel.ReadOnlyCollection<string>(_students); }
}
呢?
...全文
309 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Eddie005 2006-08-23
  • 打赏
  • 举报
回复
public ICollection<Student> students

111,097

社区成员

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

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

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