以前,我用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); }
}
呢?
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); }
}
呢?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货