IEnumerable

IEnumerable

                                      


二.IEnumerable和IEnumerable
   主要实现  public IEnumerator GetEnumerator()
 
C# 1.0中的foreach

没有迭代器的时候,创建一个可用于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{...} }
  }
 }

对集合使用foreach语句:
  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 中的迭代器

使用迭代器创建于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语句:

 Stack stack = new Stack();
 foreach(int i in statck){...}



//将数据源中的数据都转换为IEnumerable类型,用作数据绑定

//其中_dataSource为数据源,DataMember为要找的数据名称

  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;
  }





posted @ 2007-01-29 10:15  Winner.Net(2007)  阅读(1225)  评论(1编辑  收藏  举报