Make dictionary read only in C#

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

    First, you'll have to create a new dictionary with the desired content types:

    var dicWithReadOnlyList = dic.ToDictionary(
        kv => kv.Key,
        kv => kv.Value.AsReadOnly());
    

    Then you can just return the new dictionary, since IReadOnlyDictionary is a supertype of Dictionary.


    Why do you need to do that? Because Dictionary is not a supertype of Dictionary, even if A is a supertype of B. Why? Consider the following example:

    var dic = new Dictionary();
    Dictionary dic2 = dic;      // Imagine this were possible...
    
    dic2.Add(someT, someA);           // ...then we'd have a type violation here, since
                                      // dic2 = dic requires some B as the value.
    

    In other words, TValue in Dictionary is not covariant. From an object-orientied point of view, covariance should be possible in the read-only version of the dictionary, but there are legacy issues in the .NET framework which prevent this (see the part starting with "UPDATE" in this question for details).

提交回复
热议问题