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

旧巷老猫 提交于 2019-12-20 18:33:13

问题


what is the value of using IDictionary here?


回答1:


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 Dictionary class) 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.




回答2:


IDictionary enables looser coupling.

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);



回答3:


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

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.

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.



来源:https://stackoverflow.com/questions/328830/idictionarystring-string-versus-dictionarystring-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!