【问题标题】:readonly keyword does not make a List<> ReadOnly?readonly 关键字不会使 List<> ReadOnly?
【发布时间】:2012-04-21 10:36:59
【问题描述】:

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

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

.. 但即使使用readonly,我仍然可以将其他类的项目添加到列表中:

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

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

有没有办法在不改变 CharList 的实现的情况下使东西只读(它会破坏一些东西)? 如果我必须更改实现(使其不可更改),最好的方法是什么? 我需要它是 List,所以 ReadOnlyCollection 不行

【问题讨论】:

标签: c# list collections


【解决方案1】:

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

如果你希望你的对象是不可变的,你必须使用不可变的类型。您提到的类型ReadOnlyCollection&lt;T&gt; 是不可变集合的一个示例。请参阅此相关问题,了解如何为字典实现相同的目标:

【讨论】:

  • 问题提到“我需要它是 List,所以 ReadOnlyCollection 不会做”,我知道没有ReadOnlyDictionary
  • 查看我添加的链接“.NET 中是否有可用的只读通用字典?”
  • 嗯。正如该问题的答案所暗示的那样,事实证明,.NET 4.5 确实已经有了ReadOnlyDictionary。酷。
  • @hvd:很好的发现,我错过了。你投票了吗?它拥有的票数越多,人们就越有可能看到它。
【解决方案2】:

List 有 AsReadOnly 方法,返回只读列表应该是你想要的。

【讨论】:

  • 但是SortedList&lt;TKey, TValue&gt; 没有。
  • 它返回一个 ReadOnlyCollection
【解决方案3】:

只读修饰符只是保证变量'CharList'不能从类构造函数之外重新分配给其他东西。您需要创建自己的没有公共 Add() 方法的字典结构。

class ImmutableSortedList<T, T1> 
{
    SortedList<T, T1> mSortedList;

    public ImmutableSortedList(SortedList<T, T1> sortedList) // can only add here (immutable)
    {
        this.mSortedList = sortedList; 
    }

    public implicit operator ImmutableSortedList<T, T1>(SortedList<T, T1> sortedList)
    {
        return new ImmutableSortedList<T, T1>(sortedList); 
    }
}

或者,如果您确实无法更改实现,请将 SortedList 设为私有并添加您自己的方法来控制对其的访问:

class MyList
{
    // private now
    readonly SortedList<int, List<myObj>> CharList;

    // public indexer
    public List<myObj> this[int index]
    {
        get { return this.CharList[index]; }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-17
    • 2020-09-20
    • 2016-05-10
    • 2020-11-07
    • 2019-12-11
    • 2020-01-24
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多