C#中:为收藏范例封装 [英] C#: Encapsulation of for example collections
问题描述
我想知道其中哪些人会被认为是最干净的还是最好使用以及为什么。
I am wondering which one of these would be considered the cleanest or best to use and why.
其中之一暴露了乘客名单,这让用户添加和删除等其他隐藏的名单,只有让用户一一列举,并添加使用一种特殊的方法。
One of them exposes the a list of passengers, which let the user add and remove etc. The other hides the list and only let the user enumerate them and add using a special method.
例1
class Bus
{
public IEnumerable<Person> Passengers { get { return passengers; } }
private List<Passengers> passengers;
public Bus()
{
passengers = new List<Passenger>();
}
public void AddPassenger(Passenger passenger)
{
passengers.Add(passenger);
}
}
var bus = new Bus1();
bus.AddPassenger(new Passenger());
foreach(var passenger in bus.Passengers)
Console.WriteLine(passenger);
例2
Example 2
class Bus
{
public List<Person> Passengers { get; private set; }
public Bus()
{
Passengers = new List<Passenger>();
}
}
var bus = new Bus();
bus.Passengers.Add(new Passenger());
foreach(var passenger in bus.Passengers)
Console.WriteLine(passenger);
我想说的第一类是更好的封装。而在这个确切的情况下,这可能是更好的方法(因为你应该确保它留在巴士上的空间,等等)。但我想有可能是情况下,第二类可能是有用的呢?就像如果类并不真正关心,只要有一个发生的事情到该列表。你觉得呢?
The first class I would say is better encapsulated. And in this exact case, that might be the better approach (since you should probably make sure it's space left on the bus, etc.). But I guess there might be cases where the second class may be useful as well? Like if the class doesn't really care what happens to that list as long as it has one. What do you think?
推荐答案
在例如一个,有可能发生变异您的收藏。
In example one, it is possible to mutate your collection.
考虑以下几点:
var passengers = (List<Passenger>)bus.Passengers;
// Now I have control of the list!
passengers.Add(...);
passengers.Remove(...);
要解决这个问题,你可能会考虑这样的事情:
To fix this, you might consider something like this:
class Bus
{
private List<Passenger> passengers;
// Never expose the original collection
public IEnumerable<Passenger> Passengers
{
get { return passengers.Select(p => p); }
}
// Or expose the original collection as read only
public ReadOnlyCollection<Passenger> ReadOnlyPassengers
{
get { return passengers.AsReadOnly(); }
}
public void AddPassenger(Passenger passenger)
{
passengers.Add(passenger);
}
}
这篇关于C#中:为收藏范例封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!