How to get around lack of covariance with IReadOnlyDictionary?

后端 未结 5 922
庸人自扰
庸人自扰 2020-12-01 17:48

I\'m trying to expose a read-only dictionary that holds objects with a read-only interface. Internally, the dictionary is write-able, and so are the objects within (see belo

5条回答
  •  庸人自扰
    2020-12-01 18:23

    Another approach for a specific lack of covariance:

    A work around for a specific type of useful covariance on idictionary

    public static class DictionaryExtensions
        {
            public static IReadOnlyDictionary> ToReadOnlyDictionary(
                this IDictionary> toWrap)
            {
                var intermediate = toWrap.ToDictionary(a => a.Key, a =>a.Value!=null? a.Value.ToArray().AsEnumerable():null);
                var wrapper = new ReadOnlyDictionary>(intermediate);
                return wrapper;
            }   
        }
    

提交回复
热议问题