C# IDictionary<string, string> 与 Dictionary<string, string>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/328830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:23:36  来源:igfitidea点击:

IDictionary<string, string> versus Dictionary<string, string>

c#genericscollections

提问by leora

what is the value of using IDictionary here?

在这里使用 IDictionary 的价值是什么?

采纳答案by Konrad Rudolph

The value of using an interface is always the same: you don't have to change client code when switching to another backend implementation.

使用接口的价值始终相同:在切换到另一个后端实现时,您不必更改客户端代码。

Consider that profiling your code later shows that a hash table implementation (used in the Dictionaryclass) isn't suited for your task and that a binary search tree would perform better. If you've coded to an interface then switching the implementation is straightforward. If, however, you've used a concrete class, you've got to change a lot more code in a lot more places. => This costs time and money.

考虑到稍后分析您的代码表明哈希表实现(在Dictionary类中使用)不适合您的任务,并且二叉搜索树会表现得更好。如果您已对接口进行编码,则切换实现很简单。但是,如果您使用了具体类,则必须在更多地方更改更多代码。=> 这需要时间和金钱。

回答by Arjan Einbu

IDictionary enables looser coupling.

IDictionary 实现了更松散的耦合。

Say you have a method like this:

假设你有一个这样的方法:

void DoSomething(IDictionary<string, string> d)
{
   //...
}

You can use it like this:

你可以这样使用它:

Dictionary<string, string> a = new Dictionary<string, string>();
SortedDictionary<string, string> b = new SortedDictionary<string, string>();
DoSomething(a);
DoSomething(b);

回答by Cameron MacFarland

Based on your previous question Class inherits generic dictionary<string, IFoo>and Interfaceand the discussion in the answers, I'm guessing your asking more about inheriting from rather than using.

根据您之前的问题Class 继承了 genericdictionary<string, IFoo>和 Interface以及答案中的讨论,我猜您更多地询问了继承而不是使用。

Implementing from Dictionary is fine if your happy with the way dictionary is implemented. If you want to change something, then implementing IDictionary is better.

如果您对字典的实现方式感到满意,则从字典中实现是可以的。如果你想改变一些东西,那么实现 IDictionary 会更好。

IMHO if you're going to cover an existing member with 'new' then it's better to implement the interface rather than inherit from the original class.

恕我直言,如果您打算用“新”覆盖现有成员,那么最好实现接口而不是从原始类继承。