Make dictionary read only in C#

后端 未结 6 594
执笔经年
执笔经年 2020-12-18 20:24

I have a Dictionary> and would like to expose the member as read only. I see that I can return it as a IReadOnlyDictionar

6条回答
  •  悲&欢浪女
    2020-12-18 21:27

    I run into the same problem. I solved it on the following way.

    List list = new List();
    
    Dictionary> dic = new Dictionary>();
    
    IReadOnlyDictionary> dicRo = new ReadOnlyDictionary>(dic);
    
     list.Add("Test1");
    
     dic["T"] = list.AsReadOnly();
    
     ist.Add("Test2");
    

    This has the positiv effekt, that you

    • can still add items to the list
    • can still add items to the dictionary
    • can't edit the ReadOnlyDictionary
    • can't edit the ReadOnlyCollection
    • can't cast it into a Dictionary
    • can't cast it into a List
    • have your ReadOnlyDictionary always up to date

    Maybe this will help someone.

提交回复
热议问题