代码之家  ›  专栏  ›  技术社区  ›  Sinatr

如何正确使用IReadOnlyDictionary?

  •  16
  • Sinatr  · 技术社区  · 10 年前

    从…起 msdn :

    表示键/值对的通用只读集合。

    但是,请考虑以下事项:

    class Test
    {
        public IReadOnlyDictionary<string, string> Dictionary { get; } = new Dictionary<string, string>
        {
            { "1", "111" },
            { "2", "222" },
            { "3", "333" },
        };
    
        public IReadOnlyList<string> List { get; } =
            (new List<string> { "1", "2", "3" }).AsReadOnly();
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var test = new Test();
    
            var dictionary = (Dictionary<string, string>)test.Dictionary; // possible
            dictionary.Add("4", "444"); // possible
            dictionary.Remove("3"); // possible
    
            var list = (List<string>)test.List; // impossible
            list.Add("4"); // impossible
            list.RemoveAt(0); // impossible
        }
    }
    

    我很容易投 IReadOnlyDictionary Dictionary (任何人都可以)并改变它,同时 List 有漂亮的 AsReadOnly 方法

    问题:如何正确使用 IReadOnlyDictionary(只读字典) 真正公开 只读的 词典

    1 回复  |  直到 10 年前
        1
  •  20
  •   Community Mohan Dere    8 年前

    .NET 4.5引入了 ReadOnlyDictionary 您可以使用的类型。它有一个接受现有字典的构造函数。

    当以较低的框架版本为目标时,请使用包装器,如中所述 Is there a read-only generic dictionary available in .NET? Does C# have a way of giving me an immutable Dictionary? .

    请注意,当使用后一类时,集合初始值设定项语法将不起作用;被编译为 Add() 电话。

    推荐文章