IEnumerable与IEnumerator区别

2024-03-23 10:18

本文主要是介绍IEnumerable与IEnumerator区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

IEnumerator:提供在普通集合中遍历的接口,有Current,MoveNext(),Reset(),其中Current返回的是object类型。
IEnumerable: 暴露一个IEnumerator,支持在普通集合中的遍历。
IEnumerator<T>:继承自IEnumerator,有Current属性,返回的是T类型。
IEnumerable<T>:继承自IEnumerable,暴露一个IEnumerator<T>,支持在泛型集合中遍历。

1. 要使自定义的集合类型支持foreach访问,就要实现IEnumerable接口。

2. 在很多地方有讨论为什么新增加的泛型接口IEnumerable<T>要继承IEnumerable,这是为了兼容。理论上所有的泛型接口都要继承自所有的非泛型接口。例如在.net 1.1中有个方法接收的是IEnumerable类型的参数,当移植到新的环境下,我们传入一个IEnumerable<T>的参数,它也是可以被接受的,因为他们完成的都是枚举的行为。

然而特殊的是IList<T>没有继承自IList接口,因为如果让IList<T>继承IList的话,那么是实现IList<int>的类就需要实现两个Insert方法,一个是IList<int>的void Insert(int index, int item),另外一个是IList的void Insert(int index, object item),这是就有一个接口可以把object类型的数据插入到IList<int>集合中了,这是不对的,所以不继承。

而IEnumerable<T>不同的是,它只有”输出“的作用,也就是说我们只会从它里面取数据,所以不会有上面描述的混乱出现。

3. 下面的例子描述了如何使用
首先,有一个Person类:


public class Person
    {
        
public Person(string fName, string lName)
        {
            
this.firstName = fName;
            
this.lastName = lName;
        }

        
public string firstName;
        
public string lastName;
    }


第一种方式实现People集合:


public class People : IEnumerable
    {
        
private Person[] _people;
        
public People(Person[] pArray)
        {
            _people 
= new Person[pArray.Length];

            
for (int i = 0; i < pArray.Length; i++)
            {
                _people[i] 
= pArray[i];
            }
        }

        
public IEnumerator GetEnumerator()
        {
            
return new PeopleEnum(_people);
        }
    }

    
public class PeopleEnum : IEnumerator
    {
        
public Person[] _people;

        
// Enumerators are positioned before the first element
        
// until the first MoveNext() call.
        int position = -1;

        
public PeopleEnum(Person[] list)
        {
            _people 
= list;
        }

        
public bool MoveNext()
        {
            position
++;
            
return (position < _people.Length);
        }

        
public void Reset()
        {
            position 
= -1;
        }

        
public object Current
        {
            
get
            {
                
try
                {
                    
return _people[position];
                }
                
catch (IndexOutOfRangeException)
                {
                    
throw new InvalidOperationException();
                }
            }
        }
    }


第二种方式,让People自己也实现IEnumerator接口:


    public class People : IEnumerable, IEnumerator
    {
        
private Person[] _people;
        
int position = -1;

        
public People(Person[] pArray)
        {
            _people 
= new Person[pArray.Length];

            
for (int i = 0; i < pArray.Length; i++)
            {
                _people[i] 
= pArray[i];
            }
        }

        
#region IEnumerable Members

        
public IEnumerator GetEnumerator()
        {
            
return this;
        }

        
#endregion

        
#region IEnumerator Members

        
public object Current
        {
            
get 
            {
                
try
                {
                    
return _people[position];
                }
                
catch (IndexOutOfRangeException)
                {
                    
throw new IndexOutOfRangeException();
                }
            }
        }

        
public bool MoveNext()
        {
            position
++;
            
return (position < _people.Length);
        }

        
public void Reset()
        {
            position 
= -1;
        }

        
#endregion
    }


第三种方式,用泛型指定了类型:


public class People : IEnumerable<Person>, IEnumerator<Person>
    {
        
private Person[] _people;
        
int position = -1;

        
public People(Person[] pArray)
        {
            _people 
= new Person[pArray.Length];

            
for (int i = 0; i < pArray.Length; i++)
            {
                _people[i] 
= pArray[i];
            }
        }

        
#region IEnumerable<Person> Members

        
public IEnumerator<Person> GetEnumerator()
        {
            
return this;
        }

        
#endregion

        
#region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            
return this;
        }

        
#endregion

        
#region IEnumerator<Person> Members

        
public Person Current
        {
            
get
            {
                
try
                {
                    
return _people[position];
                }
                
catch (IndexOutOfRangeException)
                {
                    
throw new IndexOutOfRangeException();
                }
            }
        }

        
#endregion

        
#region IDisposable Members

        
public void Dispose()
        {
        }

        
#endregion

        
#region IEnumerator Members

        
object IEnumerator.Current
        {
            
get
            {
                
try
                {
                    
return _people[position];
                }
                
catch (IndexOutOfRangeException)
                {
                    
throw new IndexOutOfRangeException();
                }
            }
        }

        
public bool MoveNext()
        {
            position
++;
            
return (position < _people.Length);
        }

        
public void Reset()
        {
            position 
= -1;
        }

        
#endregion
    }


然后就可以用foreach对自定义集合访问了:
Person[] peopleArray = new Person[3]
            {
                
new Person("John""Smith"),
                
new Person("Jim""Johnson"),
                
new Person("Sue""Rabon"),
            };

            People peopleList 
= new People(peopleArray);
            
foreach (Person p in peopleList)
                Console.WriteLine(p.firstName 
+ " " + p.lastName);

下面介绍yield关键字的用法:

注意两点:第一,它只能用在一个iterator的方法中,也就是说这个方法的返回值类型只能是IEnumerableIEnumeratorIEnumerable<T>IEnumerator<T>;第二,它只有两种语法:yield return 表达式;或者是yield break
例如下面用yield return返回循环中每一个满足条件的值,但是并不退出方法:
public static class NumberList
{
// Create an array of integers.
public static int[] ints = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 };
// Define a property that returns only the even numbers.
public static IEnumerable<int> GetEven()
{
// Use yield to return the even numbers in the list.

foreach (int i in ints)

if (i % 2 == 0)
yield return i;
}
}

调用的地方如下:
// Display the even numbers.
Console.WriteLine("Even numbers");
foreach (int i in NumberList.GetEven())
Console.WriteLine(i);

在这种用iterator的循环中,只能用yield break退出循环(也退出了整个方法),若是用break是编译不过的。例如:
public static IEnumerable<int> GetEven()
{
// Use yield to return the even numbers in the list.

foreach (int i in ints)
if (i % 2 == 0)
yield break;

Console.WriteLine();
}
如果yield break;会被执行到的话,则后面的Console.WriteLine();是不会被执行的,整个方法体已经在yield break被执行后就退出了。

另外下面这种写法:
IEnumerable<int> GetValues()
        {
            yield return 1;
            yield return 2;
            yield return 3;
            yield return 4;
        }
则可以用
foreach (int i in this.GetValues())
            {
                Console.WriteLine(i);
            }
来输出,第一次取第一个yield return的值1,第二次取第二个yield return的值2,依此类推。

public interface IEnumerable
{
    IEnumerator GetEnumerator();
}
 
public interface IEnumerator
{
    bool MoveNext();
    void Reset();
 
    Object Current { get; }
}
 
IEnumerable和IEnumerator有什么区别?这是一个很让人困惑的问题(在很多forum里都看到有人在问这个问题)。研究了半天,得到以下几点认识:
 
1、一个Collection要支持foreach方式的遍历,必须实现IEnumerable接口(亦即,必须以某种方式返回IEnumerator object)。
 
2、IEnumerator object具体实现了iterator(通过MoveNext(),Reset(),Current)。
 
3、从这两个接口的用词选择上,也可以看出其不同:IEnumerable是一个声明式的接口,声明实现该接口的class是“可枚举(enumerable)”的,但并没有说明如何实现枚举器(iterator);IEnumerator是一个实现式的接口,IEnumerator object就是一个iterator。
 
4、IEnumerable和IEnumerator通过IEnumerable的GetEnumerator()方法建立了连接,client可以通过IEnumerable的GetEnumerator()得到IEnumerator object,在这个意义上,将GetEnumerator()看作IEnumerator object的factory method也未尝不可。


IEnumerator   是所有枚举数的基接口。  
   
  枚举数只允许读取集合中的数据。枚举数无法用于修改基础集合。  
   
  最初,枚举数被定位于集合中第一个元素的前面。Reset   也将枚举数返回到此位置。在此位置,调用   Current   会引发异常。因此,在读取   Current   的值之前,必须调用   MoveNext   将枚举数提前到集合的第一个元素。  
   
  在调用   MoveNext   或   Reset   之前,Current   返回同一对象。MoveNext   将   Current   设置为下一个元素。  
   
  在传递到集合的末尾之后,枚举数放在集合中最后一个元素后面,且调用   MoveNext   会返回   false。如果最后一次调用   MoveNext   返回   false,则调用   Current   会引发异常。若要再次将   Current   设置为集合的第一个元素,可以调用   Reset,然后再调用   MoveNext。  
   
  只要集合保持不变,枚举数就将保持有效。如果对集合进行了更改(例如添加、修改或删除元素),则该枚举数将失效且不可恢复,并且下一次对   MoveNext   或   Reset   的调用将引发   InvalidOperationException。如果在   MoveNext   和   Current   之间修改集合,那么即使枚举数已经无效,Current   也将返回它所设置成的元素。  
   
  枚举数没有对集合的独占访问权;因此,枚举一个集合在本质上不是一个线程安全的过程。甚至在对集合进行同步处理时,其他线程仍可以修改该集合,这会导致枚举数引发异常。若要在枚举过程中保证线程安全,可以在整个枚举过程中锁定集合,或者捕捉由于其他线程进行的更改而引发的异常。 

这篇关于IEnumerable与IEnumerator区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/838000

相关文章

Go之errors.New和fmt.Errorf 的区别小结

《Go之errors.New和fmt.Errorf的区别小结》本文主要介绍了Go之errors.New和fmt.Errorf的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考... 目录error的基本用法1. 获取错误信息2. 在条件判断中使用基本区别1.函数签名2.使用场景详细对

Redis中哨兵机制和集群的区别及说明

《Redis中哨兵机制和集群的区别及说明》Redis哨兵通过主从复制实现高可用,适用于中小规模数据;集群采用分布式分片,支持动态扩展,适合大规模数据,哨兵管理简单但扩展性弱,集群性能更强但架构复杂,根... 目录一、架构设计与节点角色1. 哨兵机制(Sentinel)2. 集群(Cluster)二、数据分片

一文带你迅速搞懂路由器/交换机/光猫三者概念区别

《一文带你迅速搞懂路由器/交换机/光猫三者概念区别》讨论网络设备时,常提及路由器、交换机及光猫等词汇,日常生活、工作中,这些设备至关重要,居家上网、企业内部沟通乃至互联网冲浪皆无法脱离其影响力,本文将... 当谈论网络设备时,我们常常会听到路由器、交换机和光猫这几个名词。它们是构建现代网络基础设施的关键组成

redis和redission分布式锁原理及区别说明

《redis和redission分布式锁原理及区别说明》文章对比了synchronized、乐观锁、Redis分布式锁及Redission锁的原理与区别,指出在集群环境下synchronized失效,... 目录Redis和redission分布式锁原理及区别1、有的同伴想到了synchronized关键字

JAVA覆盖和重写的区别及说明

《JAVA覆盖和重写的区别及说明》非静态方法的覆盖即重写,具有多态性;静态方法无法被覆盖,但可被重写(仅通过类名调用),二者区别在于绑定时机与引用类型关联性... 目录Java覆盖和重写的区别经常听到两种话认真读完上面两份代码JAVA覆盖和重写的区别经常听到两种话1.覆盖=重写。2.静态方法可andro

C++中全局变量和局部变量的区别

《C++中全局变量和局部变量的区别》本文主要介绍了C++中全局变量和局部变量的区别,全局变量和局部变量在作用域和生命周期上有显著的区别,下面就来介绍一下,感兴趣的可以了解一下... 目录一、全局变量定义生命周期存储位置代码示例输出二、局部变量定义生命周期存储位置代码示例输出三、全局变量和局部变量的区别作用域

MyBatis中$与#的区别解析

《MyBatis中$与#的区别解析》文章浏览阅读314次,点赞4次,收藏6次。MyBatis使用#{}作为参数占位符时,会创建预处理语句(PreparedStatement),并将参数值作为预处理语句... 目录一、介绍二、sql注入风险实例一、介绍#(井号):MyBATis使用#{}作为参数占位符时,会

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Javaee多线程之进程和线程之间的区别和联系(最新整理)

《Javaee多线程之进程和线程之间的区别和联系(最新整理)》进程是资源分配单位,线程是调度执行单位,共享资源更高效,创建线程五种方式:继承Thread、Runnable接口、匿名类、lambda,r... 目录进程和线程进程线程进程和线程的区别创建线程的五种写法继承Thread,重写run实现Runnab

C++中NULL与nullptr的区别小结

《C++中NULL与nullptr的区别小结》本文介绍了C++编程中NULL与nullptr的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编... 目录C++98空值——NULLC++11空值——nullptr区别对比示例 C++98空值——NUL