c# foreach枚举器

要是本身的类支持foreach ,必须在类中必须有GetEnumerator方法,该方法返回的是一个IEnumerator类型的枚举器;对象

public class MyStruct   
   {  
       public string[] sName = new string[] { "张三", "李四", "王五" };  
       public IEnumerator GetEnumerator()  
       {  
         return  new MyStructEnumerator(sName);  
       }  
   }    

  因此本身得写一个类类继承IEnumerator接口,并在类中实现IEnumerator接口;blog

public class MyStructEnumerator : IEnumerator  
    {  
//要遍历的对象
        private string[] sList;  
        public MyStructEnumerator(string[] get)  
        {  
            sList = get;  //获得
        }  
    //索引
        private int index = -1;  
//获取当前项
        public object Current  
        {  
            get  
            {  
                if(index>=0&&index<sList.Length)  
                {  
                    return sList[index];  
                }  
                else  
                {  
                    throw new  IndexOutOfRangeException();  
                }  
            }  
        }  
  //移到下一个
        public bool MoveNext()  
        {  
            if (index+1 < sList.Length)  
            {  
                index++;  
                return true;  
            }  
            else  
            {  
                return false;  
            }  
        }  
      //重置
        public void Reset()  
        {  
  
            index = -1;  
        }  
}  

  而后在实例化本身写的MyStruct就能够用foreach来遍历了;继承

 

   或者更方便的办法,只需在MyStrcu中添加一个方法;(方法一)索引

 

public class MyStruct   
   {  
       public string[] sName = new string[] { "张三", "李四", "王五" };  //当返回值类型是IEnumerator时,编译器会自动帮咱们生成一个“枚举类”,即实现了IEnumerator的接口的类 
       public IEnumerable GetObj()  
       {  
         for(int i=0;i<sName.Length;i++)
         {
           yield return sName[i];
          }
       }  
   }   

  而后能够直接调用foreach(string res in MyStruct.GetObj){...};接口

也能够(方法2)get

public class MyStruct         
   {  
       public string[] sName = new string[] { "张三", "李四", "王五" };  
       public IEnumerator GetEnumerator()  
       {  
         for(int i=0;i<sName.Length;i++)
         {
             yield return sName[i];
         } 
       }  
   }
       

  以后直接调用foreach(string res in MyStruct);比上面的写法看起来方便在不用再去调用GetObj方法;编译器

 方法一和方法二的区别是一个要调用方法, 方法二不用调用方法是由于类里有GetEnumerator方法,foreach会认出这个方法,而方法一没有,因此要。出方法,方法一会自动去实现IEnumerable接口.string

相关文章
相关标签/搜索