只读关键字不使List<>只读? [英] 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) };
或
MyList.CharList.Add(new List<myObj>() { new myObj(30, 30) });
有没有一种方法,使读的东西只有在不改变CharList的实现(它会打破一些东西)?
。如果我必须改变实现(使它不可更改),这将是最好的方法是什么?
我需要它是List< T,T>中这样ReadOnlyCollection还不会做。
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
推荐答案
的修改< A HREF =http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx> 只读
意味着该值不能分配的除了在声明或构造函数。它的不的意思是分配的对象将成为不可改变的。
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.
如果你希望你的对象是不可变的,你必须使用一个类型,是不可变的。类型 ReadOnlyCollection还< T>
了你提到的是一个不可改变的集合的一个例子。请参阅如何实现相同的字典此相关的问题:
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:
- Is there a read-only generic dictionary available in .NET?
这篇关于只读关键字不使List<>只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!