只读关键字不使List<>只读? [英] readonly keyword does not make a List<> ReadOnly?

查看:193
本文介绍了只读关键字不使List<>只读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个公共静态类下面的代码:

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 =htt​​p://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&LT;&GT;只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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