封装对集合成员的添加和删除操作有很多好处,所以成了一个惯用法。包括提供一个只读的getter和AddXX()、 RemoveXX()函数:
public
class
Person
{
private IList < Car > _cars = new List < Car > ();
public IList < Car > Cars
{
get { return new ReadOnlyCollection < Car > (_cars); }
}
public void AddCar(Car car)
{
_cars.Add(car);
}
}
public class Car
{
private Person _owner;
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
{
private IList < Car > _cars = new List < Car > ();
public IList < Car > Cars
{
get { return new ReadOnlyCollection < Car > (_cars); }
}
public void AddCar(Car car)
{
_cars.Add(car);
}
}
public class Car
{
private Person _owner;
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
如果函数里已经有了一个List<Car>变量,就可以使用 AsReadOnly() 函数:
public
IList
<
Car
>
Cars
{
get
{
List < Car > cars = new List < Car > (_cars);
// do some some things
return cars.AsReadOnly();
}
}
{
get
{
List < Car > cars = new List < Car > (_cars);
// do some some things
return cars.AsReadOnly();
}
}