带有默认值的.net字典

THX*_*138 3 .net dictionary

我想要一个字典,它将返回不在字典中的任何键的指定值,如:

var dict = new DictWithDefValues("not specified");
dict.Add("bob78", "Smart");
dict.Add("jane17", "Doe");
Assert.AreEqual(dict["xxx"], "not specified");
Run Code Online (Sandbox Code Playgroud)

扩展System.Collections.Generics.Dictionary并覆盖TryGetValue不起作用,因为TryGetValue不是虚拟的.

从头开始重新实现字典(来自IDictionary <,>)是太多的努力.

扩展方法不会让我用默认值"初始化"字典.我希望字典的消费者认为密钥存在,而不仅仅是dict.GetOrDefault(key, "not specified");

Ree*_*sey 7

从头开始重新实现字典(来自IDictionary <,>)是太多的努力

这真是最好的选择.只需封装一个Dictionary<,>作为类的成员,并将所有成员传递给Dictionary的代码.在这种情况下,您只需要处理希望不同的属性和方法.

我同意这是一项繁琐的工作 - 但它可能不到5分钟的打字时间,因为每个方法都可以传递给内部字典的实现.


Con*_*rix 5

我认为Reed是正确的,Reimplementing Dictionary非常简单,如果您需要的话就可以了。

但是创建一个新的类来替代它似乎仍然过高

        dict.TryGetValue("xxx", out value);
        value = value ?? "not specified";
Run Code Online (Sandbox Code Playgroud)

      value  = dict.GetOrDefault(key, "not specified")
Run Code Online (Sandbox Code Playgroud)

  • 好吧,问题在于我很少有消费者使用传递给他们的字典。这些使用者不知道(并且一定不知道,否则会违反SRP)什么是缺少条目的默认值。因此,不,它不仅是替换它,还替换它:somesomeServiceResponsibleForHandlingMissingKeys.GetValueFor(key) (4认同)