超级怪兽工厂txt下载:[C#]实现IEnumerable接口来使用foreach语句的一个实例
来源:百度文库 编辑:九乡新闻网 时间:2024/04/28 00:32:52
实现IEnumerable接口来使用foreach语句的一个实例
view sourceprint?
01
using
System;
02
using
System.Collections.Generic;
03
using
System.Linq;
04
using
System.Text;
05
using
System.Collections;
06
07
namespace
IEnumeratorSample
08
{
09
class
Person : IEnumerable
//派生自IEnumerable,同样定义一个Personl类
10
{
11
public
string
Name;
12
public
string
Age;
13
public
Person(
string
name,
string
age)
14
{
15
Name = name;
16
Age = age;
17
}
18
19
private
Person[] per;
20
public
Person(Person[] array)
//重载构造函数,迭代对象,用一个数组来存放Person的集合,在后面用foreach来访问,但是仍然要实现GetEnumerator()
21
{
22
per =
new
Person[array.Length];
23
24
for
(
int
i = 0; i < array.Length; i++)
25
{
26
per[i] = array[i];
27
}
28
}
29
30
public
IEnumerator GetEnumerator()
//实现GetEnumerator()接口
31
{
32
return
new
PersonEnum(per);
//在这里调用PersonEnum
33
}
34
}
35
36
class
PersonEnum : IEnumerator
//实现foreach语句内部,并派生
37
{
38
public
Person[] _per;
39
int
position = -1;
40
41
public
PersonEnum(Person[] list)
42
{
43
_per = list;
44
}
45
46
public
bool
MoveNext()
47
{
48
position++;
49
return
(position < _per.Length);
50
}
51
52
public
void
Reset()
53
{
54
position = -1;
55
}
56
57
public
object
Current
58
{
59
get
60
{
61
try
62
{
63
return
_per[position];
64
}
65
catch
(IndexOutOfRangeException)
66
{
67
throw
new
InvalidOperationException();
68
}
69
}
70
}
71
}
72
73
class
Program
74
{
75
static
void
Main(
string
[] args)
76
{
77
Person[] per =
new
Person[2]
//同样初始化并定义2个Person对象
78
{
79
new
Person(
"guojing"
,
"21"
),
80
new
Person(
"muqing"
,
"21"
),
81
};
82
83
Person personlist =
new
Person(per);
//初始化对象集合
84
foreach
(Person p
in
personlist)
//使用foreach语句
85
Console.WriteLine(
"Name is "
+ p.Name +
" and Age is "
+ p.Age);
86
Console.ReadKey();
87
}
88
}
89
}
[C#]实现IEnumerable接口来使用foreach语句的一个实例
RS232-C接口的应用
C源码:一个原始套接字的实例 - fanqiang.com
镜头c接口和cs接口的区别
文件夹变形 windows C 编程 一个实例
C#接口的作用实例解析 - 51CTO.COM
禁止别人使用USB接口的方法
提速本本eSATA接口 实现真正的热插拔
RS-232c接口的两机通信的问题 - C/C++ / C语言
一个好的接口设计原则1
如何用交换机实现两台电脑共用一个ADSL宽带接口上网?
使用Visal C++对通达信进行插件编程(附实例源码与接口规范) - 股软交流 - 海风...
ANSI C 字符串库函数的实现
会计使用的EXCEL实例和技巧
470条会计使用的EXCEL实例
一个很好的用递归来完成的C简单的计算器程序
EXCEL中实现跨表关联查询的应用实例
标准C语言实现一个图书管理系统-C语言技术文档 - Firnow
禁止别人使用USB接口
【转】 使用SQLite3学习SQL语句的使用
一个双重存活者偏差的实例?
快客电邮c独创的QCP接口技术,是征服了漏洞的先知
Linux 内核使用的 GNU C 扩展
Log4j使用实例