我有这样一段代码:问题与私人集列表属性
public List<IVehicle> Vehicles { get; private set; }
我的问题是,即使我使用的是私有组,为什么我仍然可以添加值到这个列表。
我有这样一段代码:问题与私人集列表属性
public List<IVehicle> Vehicles { get; private set; }
我的问题是,即使我使用的是私有组,为什么我仍然可以添加值到这个列表。
使用时使用private set
这意味着什么是属性本身是从类的外部非可置,而不是它的方法不可用,并List<T>.Add()
只有一个方法编译器一无所知。
例如:
public class VehicleContainer{
public List<IVehicle> Vehicles { get; private set; }
...
}
....
VehicleContainer vc = new VehicleContainer();
vc.Vehicles = new List<IVehicle>() // this is an error, because of the private set
int x = vc.Vehicles.Count; // this is legal, property access
vc.Vehicles.Add(new Vehicle()); //this is legal, method call
看看at this question,其中使用ReadOnlyCollection
类中的情况下,当你想限制访问集合本身说明,以及参考了集合。
您只能在List<IVehicle>
的包含类/结构中实例化它。但是一旦你有了一个实例,你甚至可以在外面添加项目,因为这个对象是公开可见的。
对于私人Set
,您不能将该列表设置为您班级以外的新列表。例如,如果你有这个名单中的一类:
class SomeClass
{
public List<IVehicle> Vehicles { get; private set; }
}
然后同时使用:
SomeClass obj = new SomeClass();
obj.Vehicles = new List<IVehicle>(); // that will not be allowed.
// since the property is read-only
它不会阻止你评估列表上的Add
方法。例如
obj.Vehicles.Add(new Vehicle()); // that is allowed
要回报只读列表你可以看看List.AsReadOnly Method
.Add()
是在类List<>
等你以后get
列表,你可以调用该函数的函数。您不能用另一个替换列表。
你可能会返回一个IEnumerable<IVehicle>
,这将使列表(sortof)只读。
名单上调用.AsReadOnly()
将导致真正的只读列表
private List<IVehicle> vehicles;
public IEnumerable<IVehicle> Vehicles
{
get { return vehicles.AsReadOnly(); }
private set { vehicles = value; }
}
那么,它会排序*使其成为只读...但调用者仍然可以投射。 –
是的,这是真的。更新了答案。 – albertjan
getter和setter方法适用于情况;而不是实例的属性。一个例子;
Vehicles = new List<IVehicle>(); //// this is not possible
但是如果有一个实例可以改变它的属性。
由于private set;
不允许您直接设置列表,但您仍然可以调用此列表的方法,因为它使用getter。您接下来可能要使用:
//use this internally
private List<IVehicle> _vehicles;
public ReadOnlyCollection<IVehicle> Vehicles
{
get { return _vehicles.AsReadOnly(); }
}
return'Vehicles.AsReadOnly' in'get' –