IEnumerable与数组之间的关系 [英] Relation between IEnumerable and arrays

查看:57
本文介绍了IEnumerable与数组之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET IEnumerable之所以如此特别,是因为可以将诸如数组之类的编译器类型作为自变量传递给它,而它是类库接口.后台有某种继承吗?

What makes .Net IEnumerable so special that compiler types like arrays can be passed as an argument in its place with it being a class library interface. Is there some sort of inheritance in the background?

当数组可以互换地替换集合或IEnumerable作为参数时,实际上会发生什么:

What actually happens when an array can interchangeably replace a collection or IEnumerable as a parameter:

public void DoJob(IEnumerable<Job> jobs)
{
}

类似于此方法调用:

Job job = new Job();
DoJob(new [] { job });

推荐答案

由于您来自Java,因此我将首先告诉您,在C#中,存在一个统一的类型系统,其中每种类型都源自 object ,不同于Java中存在特殊的基元".

Since you came from Java, I will start by telling you that in C#, there is a unified type system, where every type derives from object, unlike in Java where there are special "primitives".

因此在C#中,数组只是另一种类型.谁说他们不能实现接口?他们能!编译器提供的全部只是一些用于创建它们的语法.实际上,数组的类型为 System.Array .

So in C#, arrays are just another type. Who says they can't implement interfaces? They can! All the compiler provides is some syntax for creating them. In actuality, arrays' type is System.Array.

这是它的声明:

public abstract class Array : ICloneable, IList, ICollection, 
    IEnumerable, IStructuralComparable, IStructuralEquatable

看到其中的 IEnumerable 吗?

对于 IEnumerable< T> ,我们可以在语言规范中找到它:

For IEnumerable<T>, we can find it in the language spec:

第12.1.2节:

一维数组T []实现接口System.Collections.Generic.IList(简称IList)及其基础接口.

A one-dimensional array T[] implements the interface System.Collections.Generic.IList (IList for short) and its base interfaces.

IList< T> 实现 IEnumerable< T> .

这篇关于IEnumerable与数组之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆