Make dictionary read only in C#

后端 未结 6 596
执笔经年
执笔经年 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:13

    It would be as easy as casting the whole dictionary reference to IReadOnlyDictionary> because Dictionary implements IReadOnlyDictionary.

    BTW, you can't do that because you want the List values as IReadOnlyList.

    So you need something like this:

    var readOnlyDict = (IReadOnlyDictionary>)dict.ToDictionary(pair => pair.Key, pair => pair.Value.AsReadOnly());
    

    Immutable dictionaries

    This is just a suggestion, but if you're looking for immutable dictionaries, add System.Collections.Immutable NuGet package to your solution and you'll be able to use them:

    // ImmutableDictionary>
    var immutableDict = dict.ToImmutableDictionary(pair => pair.Key, pair => pair.Value.ToImmutableList());
    

    Learn more about Immutable Collections here.

提交回复
热议问题