Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

c# - readonly keyword does not make a List<> ReadOnly?

I have the following code in a public static class:

public static class MyList
{
    public static readonly SortedList<int, List<myObj>> CharList;
    // ...etc.
}

.. but even using readonly I can still add items to the list from another class:

MyList.CharList[100] = new List<myObj>() { new myObj(30, 30) };

or

MyList.CharList.Add(new List<myObj>() { new myObj(30, 30) });

Is there a way to make the thing read only without changing the implementation of CharList (it'll break some stuff)? If I do have to change the implementation (to make it non-changeable), what would be the best way? I need it to be List<T, T>, so ReadOnlyCollection won't do

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The modifier readonly means that the value cannot be assigned except in the declaration or constructor. It does not mean that the assigned object becomes immutable.

If you want your object to be immutable, you must use a type that is immutable. The type ReadOnlyCollection<T> that you mentioned is an example of a immutable collection. See this related question for how to achieve the same for dictionaries:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...