实现IEnumerable接口的类可以进行简单迭代,例如foreach语句
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace IEnumerable接口
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            A a 
= new A();
            
foreach (int? var in a)//当int值可能被赋空值时用?

            
{
                Console.WriteLine(var);
                
            }


        }

    }

    
class A : IEnumerable
    
{
        
int x = 1;
        
int y = 2;
        
int z = 3;
        
public IEnumerator GetEnumerator()
        
{
           
// int i = -1;
            for (int i = 0; i <=3; i++)
            
{


                
if (i == x)
                
{
                    yield 
return 1;
                }

                
else if (i == y)
                
{
                    yield 
return 2;

                }

                
else if (i == z)
                
{
                    yield 
return 3;

                }

                
else
                
{
                    yield 
return null;
                }

            }

        }

    }

}

posted on 2007-08-18 10:49  ATP.NET  阅读(848)  评论(0编辑  收藏  举报