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

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

问题描述

我在公共静态类中有以下代码:

I have the following code in a public static class:

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

.. 但即使使用 readonly 我仍然可以将项目从另一个类添加到列表中:

.. 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,所以 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

推荐答案

修饰符 readonly 意味着该值不能被赋值,除非在声明或构造函数中.它意味着分配的对象变得不可变.

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 类型提到的是一个不可变集合的例子.请参阅此相关问题以了解如何为字典实现相同的目标:

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:

这篇关于readonly 关键字不会生成 List&lt;&gt;只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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