IEnumerable
在平常的代碼編寫(xiě)中,雖然不常用到Ienumerable 但卻不可不知他的意義,有些時(shí)候使用會(huì)起到意想不到的作用,
我們從中可以知道 foreach 在IL中,是以Ienumberable 來(lái)體現(xiàn)的。
IEnumerable和IEnumerable
?? 主要實(shí)現(xiàn)? public IEnumerator GetEnumerator()
C# 1.0中的foreach
沒(méi)有迭代器的時(shí)候,創(chuàng)建一個(gè)可用于foreach的集合(C# 1.0):
public class MyCollection : IEnumerable
{
? public MyEnumerator GetEnumerator()
? {
?? return new MyEnumerator(this);
? }
? public class MyEnumerator : IEnumerator
? {
?? public void Reset(){...}
?? public bool MoveNext(){...}
?? public int Current{ get{...} }
?? object IEnumerator.Current{ get{...} }
? }
}
對(duì)集合使用foreach語(yǔ)句:
? foreach(int i in col){...}
相單于:
IEnumerator etor = ((IEnumerable)col).GetEnumerator();
try
{
? while(etor.MoveNext())
? {
?? ElementType clem (ElementType)etor.Current;
?? ...;
? }
}
finally{(IDisposable)enumerator).Dispose();}
C# 2.0 中的迭代器
使用迭代器創(chuàng)建于foreach的集合(C# 2.0):
public class Stack:IEnumerable
{
? T[] items;
? int count;
? public void Push(T data){...}
? public T Pop(){...}
? public IEnumerator GetEnumerator()
? {
?? for(int i=count-1;i>=0;--i)
?? {
???? yield return items[i];
?? }
? }
}
使用foreach語(yǔ)句:
Stack stack = new Stack();
foreach(int i in statck){...}
- 2006年02月(5)
數(shù)據(jù)源轉(zhuǎn)成IEnumerable類(lèi)型
//將數(shù)據(jù)源中的數(shù)據(jù)都轉(zhuǎn)換為IEnumerable類(lèi)型,用作數(shù)據(jù)綁定
//其中_dataSource為數(shù)據(jù)源,DataMember為要找的數(shù)據(jù)名稱(chēng)
? protected virtual IEnumerable GetDataSource()
? {
?? if(_dataSource == null)
?? {
??? return null;
?? }
?? IEnumerable resolvedDataSource = _dataSource as IEnumerable;
?? if(resolvedDataSource != null)
?? {
??? return resolvedDataSource;
?? }
?? IListSource listSource = _dataSource as IListSource;
?? if(listSource != null)
?? {
??? IList memberList = listSource.GetList();
??? int i = memberList.Count;
??? if(listSource.ContainsListCollection == false)
??? {
???? return (IEnumerable)memberList;
??? }
??? ITypedList typedMemberList = memberList as ITypedList;
??? if(typedMemberList != null)
??? {
???? PropertyDescriptorCollection propDescs = typedMemberList.GetItemProperties(new PropertyDescriptor[0]);
???? PropertyDescriptor memberProperty = null;
???? if((propDescs != null) && (propDescs.Count!=0))
???? {
????? string dataMember = DataMember;
????? if(dataMember.Length == 0)
????? {
?????? memberProperty = propDescs[0];
????? }
????? else
????? {
?????? memberProperty = propDescs.Find(dataMember,true);
????? }
????? if(memberProperty != null)
????? {
?????? object listRow = memberList[0];
?????? object list = memberProperty.GetValue(listRow);
?????? if(list is IEnumerable)
?????? {
??????? return (IEnumerable)list;
?????? }
????? }
????? throw new Exception("no Datamember.");
???? }
???? throw new Exception("no datamember.");
??? }
?? }
?? return null;
? }
轉(zhuǎn)載于:https://www.cnblogs.com/hsapphire/archive/2010/04/16/1713211.html
總結(jié)
以上是生活随笔為你收集整理的IEnumerable的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Visual C#常用函数和方法集汇总
- 下一篇: 新云网站管理系统最新版注入漏洞