简体   繁体   English

IEnumerator vs IEnumerator <T>

[英]IEnumerator vs IEnumerator<T>

I'm fairly new to c sharp and was looking for an answer to the following: 我对c sharp很新,并且正在寻找以下答案:

Why would you want to implement IEnumerator<T> when you have IEnumerator ? 当你有IEnumerator时,为什么要实现IEnumerator<T> IEnumerator returns back the item from the collection as type object, so caters for all types. IEnumerator将集合中的项目作为类型对象返回,因此适合所有类型。

Thanks 谢谢

[The non-genericized] IEnumerator returns back the item from the collection as type object, so caters for all types. [非泛化] IEnumerator将集合中的项目作为类型对象返回,因此适合所有类型。

That's exactly the problem. 这正是问题所在。 You now know nothing about the objects that are in the sequence. 您现在对序列中的对象一无所知 They could be anything and so you have to be able to deal with anything coming out of that sequence. 它们可以是任何东西 ,所以你必须能够处理那些序列中出现的任何东西 If you have a sequence of giraffes, or a sequence of customers, or a sequence of integers, then you know that every element in the sequence will be a giraffe, customer, integer, whatever. 如果你有一系列长颈鹿,或一系列顾客,或一系列整数,那么你就会知道序列中的每个元素都是长颈鹿,顾客,整数等等。 If you have a sequence of objects then you have to write code that checks what kind of thing each of those objects is. 如果你有一系列对象,那么你必须编写代码来检查每个对象是什么类型的东西。

Having type information enables the compiler to thread that information through the system. 具有类型信息使编译器能够通过系统对该信息进行处理。 Suppose we have an IEnumerable<Customer> . 假设我们有一个IEnumerable<Customer> So everything in the sequence is a customer. 因此序列中的所有内容都是客户。 If we then say: 如果我们说:

var first = customers.First();
var address = first.Address;

Now the compiler can deduce that first is a Customer , and know that customers have addresses, and so the second line is legal. 现在,编译器可以推断出firstCustomer ,并且知道客户有地址,因此第二行是合法的。 If customers were just IEnumerable then the compiler cannot prove that your program is typesafe! 如果customers只是IEnumerable那么编译器无法证明您的程序是类型安全的!

Also, some types exhibit a performance penalty called the "boxing penalty" when treated as object . 此外,某些类型在被视为object时表现出称为“拳击惩罚”的性能惩罚。 Having a generically-typed collection eliminates that penalty. 拥有一般类型的收藏消除了这种惩罚。

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

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