readonly keyword does not make a List<> ReadOnly?

后端 未结 3 1904
心在旅途
心在旅途 2020-12-01 14:17

I have the following code in a public static class:

public static class MyList
{
    public static readonly SortedList> CharList         


        
相关标签:
3条回答
  • 2020-12-01 14:24

    The List have the AsReadOnly method that return a read only list should be what you want.

    0 讨论(0)
  • 2020-12-01 14:33

    The readonly modifier just gaurantees that the variable 'CharList' cannot be re-assigned to something else from outside of the class constructor. You need to create your own dictionary structure that doesn't have a public Add() method.

    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); 
        }
    }
    

    Or, if you truly can't change the implementation, make the SortedList private and add your own methods that control access to it:

    class MyList
    {
        // private now
        readonly SortedList<int, List<myObj>> CharList;
    
        // public indexer
        public List<myObj> this[int index]
        {
            get { return this.CharList[index]; }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 14:41

    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:

    • Is there a read-only generic dictionary available in .NET?
    0 讨论(0)
提交回复
热议问题