1

我有这段代码:

public List<IVehicle> Vehicles { get; private set; }

我的问题是即使我使用的是私有集,为什么我仍然可以向这个列表添加值。

4

6 回答 6

2

使用 private 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 方法

于 2012-12-06T07:43:09.533 回答
1

.Add()是类上的一个函数,List<>因此在get列表之后您可以调用该函数。您不能将列表替换为另一个列表。

您可以返回一个IEnumerable<IVehicle>使列表(排序)只读的。

调用.AsReadOnly()列表将导致一个真正的只读列表

private List<IVehicle> vehicles;

public IEnumerable<IVehicle> Vehicles 
{ 
    get { return vehicles.AsReadOnly(); }
    private set { vehicles = value; }
}
于 2012-12-06T07:44:00.543 回答
1

因为private set;不允许您直接设置列表,但您仍然可以调用此列表的方法,因为它正在使用 getter。您可能想使用下一个:

    //use this internally
    private List<IVehicle> _vehicles;

    public ReadOnlyCollection<IVehicle> Vehicles
    {
        get { return _vehicles.AsReadOnly(); }
    }
于 2012-12-06T07:48:04.833 回答
0

Getter 和 setter 在实例上工作;不在实例的属性上。一个例子;

Vehicles = new List<IVehicle>(); //// this is not possible

但如果有一个实例,则可以更改其属性。

于 2012-12-06T07:44:42.277 回答
0

当使用 use a 时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

看看这个问题,在ReadOnlyCollection你想限制对集合本身的访问以及对集合的引用的情况下,解释了类的使用。

于 2012-12-06T07:48:51.553 回答
-1

您只能在List<IVehicle>. 但是一旦你有了一个实例,你甚至可以在外面添加项目,因为这个对象是公开可见的。

于 2012-12-06T07:43:06.497 回答