readonly keyword does not make a List<> ReadOnly?

后端 未结 3 1914
心在旅途
心在旅途 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: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 
    {
        SortedList mSortedList;
    
        public ImmutableSortedList(SortedList sortedList) // can only add here (immutable)
        {
            this.mSortedList = sortedList; 
        }
    
        public implicit operator ImmutableSortedList(SortedList sortedList)
        {
            return new ImmutableSortedList(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> CharList;
    
        // public indexer
        public List this[int index]
        {
            get { return this.CharList[index]; }
        }
    }
    

提交回复
热议问题