Posted on 2009-08-04 13:53
Hero 閱讀(225)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
C#積累
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace Yield
6 {
7 class Yield
8 {
9 public static class NumberList
10 {
11 // 創(chuàng)建一個(gè)整數(shù)數(shù)組。
12 public static int[] ints = { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 };
13
14 // 定義一個(gè)僅返回偶數(shù)的屬性。
15 public static IEnumerable<int> GetEven()
16 {
17 // 使用 yield 返回列表中的偶數(shù)。
18 foreach (int i in ints)
19 if (i % 2 == 0)
20 yield return i;
21 }
22
23 // 定義一個(gè)僅返回奇數(shù)的屬性。
24 public static IEnumerable<int> GetOdd()
25 {
26 // 使用 yield 僅返回奇數(shù)。
27 foreach (int i in ints)
28 if (i % 2 == 1)
29 yield return i;
30 }
31 }
32
33 static void Main(string[] args)
34 {
35
36 // 顯示偶數(shù)。
37 Console.WriteLine("Even numbers");
38 foreach (int i in NumberList.GetEven())
39 Console.WriteLine(i);
40
41 // 顯示奇數(shù)。
42 Console.WriteLine("Odd numbers");
43 foreach (int i in NumberList.GetOdd())
44 Console.WriteLine(i);
45 }
46 }
47 }