Restricting access to method calls on read-only properties

淺唱寂寞╮ 提交于 2019-11-30 23:54:30

The reference is "readonly", the the actual object. I.e. you can't replace the reference with another object. So if you have a class that breaks it like this:

public class Container
{
    private readonly  List<int> _myList;

    public List<int> MyList
    {
        get { return _myList;}
    }

    public Container() : base ()
    {
        _myList = new List<int>();
    }

    public void BreakReadOnly()
    {
        _myList = new List<int>();
    }
}

…then it won't even compile. It's because a readonly field can't be reassigned with any other object. In this case BreakReadOnly will try to assign a new list.

If you really want a readonly collection of it then you can do it like this:

    public ReadOnlyCollection<int> MyList
    {
        get { return _myList.AsReadOnly(); }
    }

Hope this helps.

Updated: Removed use of IEnumerable.

Don't return a direct reference to your list. Instead return a ReadOnlyCollection wrapped around it, or if the List<> return type is set in stone, return a copy of your list. They can do whatever they want to the copy without affecting the original.

You could return a readonly Collection like this:

    public ReadOnlyCollection<int> MyList
    {
        get { return _myList.AsReadOnly(); }
    }

or return a new List so that the caller can change the list without changing the original list.

    public List<int> MyList
    {
        get { return new List<int>(_myList)}
    }

Have a look at the static Array.AsReadOnly() method, which you can use to return a wrapper around an array that prevents it from being modified.

You want _myList, which is a reference type to be readonly. Well, it is readonly and there is no defeat of the readonly concept.

The CLR implements a readonly property for reference types in such a way that the reference(pointer to the object if you want) is what is made readonly while the object to which the reference is pointing can be modified.

To work around this, you would need to make the member fields of the object themselves, readonly, because you cannot make the whole object readonly by attaching a readonly flag to the object's reference.

You can implement your on immutable generic collection class which would behave the same way as the List<> object but having readonly members.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!