Make dictionary read only in C#

后端 未结 6 808
一向
一向 2020-12-18 20:37

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:05

    If you want to return a read only dictionary but still be able to mutate the dictionary and list in your class you could use casting to get back the list type.

    This example is a bit contrived, but shows how it could work.

    public class MyClass
    {
        Dictionary> _dictionary;
        public IReadOnlyDictionary> Dictionary { get { return _dictionary; } }
    
        public MyClass()
        {
            _dictionary = new Dictionary>();
        }
    
        public void AddItem(string item)
        {
            IReadOnlyList readOnlyList = null;
            List list = null;
            if (!_dictionary.TryGetValue(item, out readOnlyList))
            {
                list = new List();
                _dictionary.Add(item, list);
            }
            else
                list = readOnlyList as List;
            list.Add(item);
        }
    }
    

    If you goal is to have the property be immutable, then using a ReadOnlyDictionary would be the best option.

提交回复
热议问题