简体   繁体   English

IEnumerable与Dictionary C#之间的区别

[英]difference between IEnumerable vs Dictionary C#

If you go to this link in stackoverflow . 如果您在stackoverflow中转到此链接 There is a question about converting an Ienrumerable to Dictionary. 关于将“可加密的”转换为“字典”存在一个问题。 So my question is why would we need IEnumerable when we have the dictionary object? 所以我的问题是,当我们拥有字典对象时,为什么我们需要IEnumerable?

Actually, i am trying to figure out what is the difference between them. 实际上,我正在尝试找出它们之间的区别。

IEnumerable is an interface . IEnumerable是一个interface An interface can not be instantiated by itself, but have to be instantiated as a class that implements the given interface. 接口不能单独实例化,而必须作为实现给定接口的类实例化。

Dictionary is a hash-map datastructure that implements the IEnumerable interface, hence it have all the methods and properties that the IEnumerable interface requires its implementations to have, making it possible to Enumerate the Dictionary structure. Dictionary是实现IEnumerable接口的hash-map结构,因此它具有IEnumerable接口要求其实现具有的所有方法和属性,从而可以Enumerate Dictionary结构。

In short: IEnumerable is an interface and Dictionary is a class implementing the interface. 简而言之:IEnumerable是一个接口,Dictionary是实现该接口的类。

well, the question you've linked is on the opposite question. 好吧,您链接的问题是相反的问题。 how to convert from IEnumerable to a Dictionary . 如何从IEnumerable转换为Dictionary why will we convert the other way around? 我们为什么要转换另一种方式? we will probably won't. 我们可能不会。 but you can also ask why will someone convert a specific class to object? 但您也可以问为什么有人将特定的类转换为对象?

the answer is the sometimes you want to have a variable/method parameter/ class member that can be one of many things: a dictionary or something else. 答案是有时您想拥有一个变量/方法参数/类成员,该成员可以是很多东西之一:字典或其他东西。 for that you might use IEnumerable . 为此,您可以使用IEnumerable

So my question is why would we need IEnumerable when we have the dictionary object? 所以我的问题是,当我们拥有字典对象时,为什么我们需要IEnumerable?

The question you've referred is about opposite: creating Dictionary from IEnumerable . 您提到的问题是相反的: IEnumerable创建Dictionary So you have IEnumerable and you'd like to have Dictionary . 因此,您拥有IEnumerable并且希望拥有Dictionary

It can be required when you have eg e List and you'd like to have quicker access to collection elements by one of the items property value. 当您拥有例如e List并希望通过items属性值之一更快地访问集合元素时,可能需要使用它。

And just to be sure, Dictionary<TKey, TValue> already implements IEnumerable<T> , so the conversion would not necessary in the opposite direction (unless you're trying to change the T ). 并且可以肯定的是, Dictionary<TKey, TValue>已经实现了IEnumerable<T> ,因此转换不需要朝相反的方向进行(除非您尝试更改T )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM