在使用get属性公开List的同时,如何使List的Add方法受到保护? [英] How to make List's Add method protected, while exposing List with get property?

查看:97
本文介绍了在使用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.

这篇关于在使用get属性公开List的同时,如何使List的Add方法受到保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆