GetNumerator实际上已经内置于 foreach in 里了下面是例子:
另外关于语法上还有一点 :对于高级语言基本上都是相似的:
string 虽然可以像in类型一样赋值,但是int是保存在栈上的,而String是保存在堆上的,是一种另类,就是特殊引用!但是其操作和int类型一样! 所以我们在写程序的时候要注意,为了避免内存泄露,一定要将删除某个带String变量的时候需要将string的值变为 "" 虽然它不太明显,但好的程序是必要的!!
Hellow.cs :
using System;
using System.Collections;
namespace Wrox.ProCSharp.Arrays
{
public class Hello
{
public IEnumerator GetEnumerator()
{
yield return "Hello";
yield return "World";
}
}
}
主程序:
using System;
using System.Collections.Generic;
using System.Text;
namespace Wrox.ProCSharp.Arrays
{
class Program
{
static void Main()
{
Hello obj = new Hello();
foreach (string s in obj)
{
Console.WriteLine(s);
}
}
}
}
//输出结果为 : Hellow
World
MSDN上例子:
using System;
public class SamplesArray {
public static void Main() {
// Creates and initializes a new Array.
String[] myArr = new String[10];
myArr[0] = "The";
myArr[1] = "quick";
myArr[2] = "brown";
myArr[3] = "fox";
myArr[4] = "jumped";
myArr[5] = "over";
myArr[6] = "the";
myArr[7] = "lazy";
myArr[8] = "dog";
// Displays the values of the Array.
int i = 0;
System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
Console.WriteLine( "The Array contains the following values:" );
while (( myEnumerator.MoveNext() ) && ( myEnumerator.Current != null ))
Console.WriteLine( "[{0}] {1}", i++, myEnumerator.Current );
}
}
/*
This code produces the following output.
The Array contains the following values:
[0] The
[1] quick
[2] brown
[3] fox
[4] jumped
[5] over
[6] the
[7] lazy
[8] dog
*/