您的位置:首页 > 其它

IEnumerable接口与IEnumerator

2010-11-11 22:51 381 查看
1.如果要迭代一个类,可以使用方法GetEnumerator(),使其返回类型是IEnumerator
2.如果要迭代一个类成员,例如一个方法,则使用IEnumerable
 
//使用IEnumerable
using System;
using System.Collections;
namespace MyEx
{
public class IEnumerableDemo
{
public static IEnumerable SimpleList()
{
yield return "string 1";
yield return "string 2";
yield return "string 3";
yield return "string 4";
}
public static void Main(string[] args)
{
Console.WriteLine("use IEnumerable.notice IEnumerable uses in method");
foreach (string item in SimpleList())
{
Console.WriteLine(item);
}
}
}
}
 
 
//使用GetEnumerator
using System;
using System.Collections;
namespace MyEx
{
public class Primes
{
private long _min;
private long _max;
private Primes()
{
}
public Primes(long min, long max)
{
if (min < 2)
{
this._min = 2;
}
else if (min >= max&&max >= 2)
{
this._min = max;
this._max = min;
}
else if (min >= max && max < 2)
{
this._min = 2;
this._max = min;
}
else
{
this._min = min;
this._max = max;
}
}
public IEnumerator GetEnumerator()
{
for (long possiblePrime = this._min; possiblePrime <= this._max;possiblePrime++)
{
bool isPrime = true;
for (long possibleFactor = 2; possibleFactor <= (long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++)
{
if (possiblePrime % possibleFactor == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
yield return possiblePrime;
}
}
}

}
public class GetEnumerableDemo
{
public static void Main(string[] args)
{
long min = Convert.ToInt32(args[0]);
long max = Convert.ToInt32(args[1]);
Primes primes = new Primes(min, max);
Console.WriteLine("begin to print prime!");
foreach (long i in primes)
{
Console.WriteLine(i);
}
Console.WriteLine("printing prime is over!");
}
}

}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string printing class