GetNumerator的使用

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

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值