列表属性中的私有集问题

时间:2012-12-06 07:41:35

标签: c#

我有这段代码:

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

我的问题是即使我使用私人套装,为什么我仍然可以在此列表中添加值。

6 个答案:

答案 0 :(得分:2)

使用私人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

答案 1 :(得分:1)

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

你可以返回一个IEnumerable<IVehicle>,它会使列表(sortof)只读。

在列表上调用.AsReadOnly()会产生一个真正的只读列表

private List<IVehicle> vehicles;

public IEnumerable<IVehicle> Vehicles 
{ 
    get { return vehicles.AsReadOnly(); }
    private set { vehicles = value; }
}

答案 2 :(得分:1)

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

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

    public ReadOnlyCollection<IVehicle> Vehicles
    {
        get { return _vehicles.AsReadOnly(); }
    }

答案 3 :(得分:0)

Getters和setter适用于实例;而不是实例的属性。一个例子;

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

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

答案 4 :(得分:0)

当使用时使用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类的情况。

答案 5 :(得分:-1)

您只能在List<IVehicle>的包含类/结构中实例化它。但是一旦你有了一个实例,你甚至可以在外面添加项目,因为该对象是公开可见的。

相关问题