在使用get属性公开List的同时,如何使List的Add方法受到保护?
我有一个名为WhatClass的类,其中有List字段.我需要能够只读该字段,所以我使用了get属性将其公开给其他对象.
I have a class named WhatClass that has List field in it. I need to be able to read-only this field, so I used a get property to expose it to other objects.
public class WhatClass
{
List<SomeOtherClass> _SomeOtherClassItems;
public List<SomeOtherClass> SomeOtherClassItems { get { return _SomeOtherClassItems; } }
}
但是事实证明,任何对象都可以调用
However it turns out that any object can call
WhatClass.SomeOtherClassItems.Add(item);
如何防止这种情况?
正如其他人所说,您正在寻找.AsReadOnly()
扩展方法.
As others have said, you are looking for the .AsReadOnly()
extension method.
但是,您应该存储对集合的引用,而不是在每次访问属性时创建它:
However, you should store a reference to the collection instead of creating it during each property access:
private readonly List<SomeOtherClass> _items;
public WhatClass()
{
_items = new List<SomeOtherClass>();
this.Items = _items.AsReadOnly();
}
public ReadOnlyCollection<SomeOtherClass> Items { get; private set; }
这是为了确保x.Items == x.Items
成立,否则对于API使用者来说可能是非常意外的.
This is to ensure that x.Items == x.Items
holds true, which could otherwise be very unexpected for API consumers.
公开ReadOnlyCollection<>
可将您的只读收藏意图传达给消费者.对_items
所做的更改将反映在Items
中.
Exposing ReadOnlyCollection<>
communicates your intent of a read-only collection to consumers. Changes to _items
will be reflected in Items
.