How to get around lack of covariance with IReadOnlyDictionary?

后端 未结 5 920
庸人自扰
庸人自扰 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:29

    Maybe this solutions works for you:

    public class ExposesReadOnly
    {
        private IDictionary InternalDict { get; set; }
        public IReadOnlyDictionary PublicList
        {
            get
            {
                IReadOnlyDictionary dictionary = new ReadOnlyDictionary(InternalDict);
    
                return dictionary;
            }
        }
    
        private class NotReadOnly : IReadOnly
        {
            public string Name { get; set; }
        }
    
        public void AddSomeValue()
        {
            InternalDict = new Dictionary();
            InternalDict.Add(1, new NotReadOnly() { Name = "SomeValue" });
        }
    }
    
    public interface IReadOnly
    {
        string Name { get; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            ExposesReadOnly exposesReadOnly = new ExposesReadOnly();
            exposesReadOnly.AddSomeValue();
    
            Console.WriteLine(exposesReadOnly.PublicList[1].Name);
            Console.ReadLine();
    
            exposesReadOnly.PublicList[1].Name = "This is not possible!";
        }
    }
    

    Hope this helps!

    Greets

提交回复
热议问题