foreach对数据的处理是怎样进行的,希望大家帮一下

xueyuanlang_fushuai 2009-02-28 09:05:37
foreach (string var in students.Keys)
{
Console.WriteLine(var);
}
var具体是什么参数,
如果仅是一个形参那么为什么会不允许修改
他到底是怎样从集合中取数据的
又是否copy了副本
foreach (object var in students.Keys)
{
Console.WriteLine(var);
}
...全文
295 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
我的QQ351091855
  • 打赏
  • 举报
回复
8楼,9楼和10楼好像懂我的意思,但我不懂你的意思,请讲详细一点好吗
lihu2651 2009-03-01
  • 打赏
  • 举报
回复
C#的foreach语句不会解析为IL代码中的foreach语句,C#编译器会把foreach语句转换为IEnumerable接口的方法和属性,这就是为什么在C#中用foreach语句循环的集合对像都必需实现IEnumerable的原因
假设有下面的foreach循环:
foreach(Person p in Persons)
{
Console.Write(p);
}
foreach语句会解析为下面的代码段。首先,调用GetEnumerator()方法,获得数组的一个枚举。然后再使用while循环:
IEnumerator enumerator = persons.GetEnumerator();
while(enumerator.MoveNext())
{
Person p = (Person)enumerator.Current;
Console.Write(p);
}
所以foreach (string var in students.Keys) 中var的数据类型必需和students.Keys的数据类型一致,因为我们看到上面解析的中间代码里是采用强制转换将枚举对像值转换为你定义的对像,如果你声明的对像不一致就会报错了。
chengfong 2009-02-28
  • 打赏
  • 举报
回复
(其实它就是在.net中实现了迭带器模式其实也可以自定义实现这个模式这两个接口)
public interface IEnumerable{ IEnumerator GetEnumerator();}
public interface IEnumerator
{ bool MoveNext(); void Reset();
Object Current { get; }}

在方法中用yield return就可以实现这个直定义的迭带器.


(平常的用法)

class 小方 {
static void Main(string[] args)
{
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
System.Console.WriteLine(i);
}
}
}
输出
0
1
2
3
5
8
13
Dobzhansky 2009-02-28
  • 打赏
  • 举报
回复
foreach 借助于 IEnumerator 工作,

下面有个讨论:
When should I use IEnumerator for looping in c#?
http://stackoverflow.com/questions/456433/when-should-i-use-ienumerator-for-looping-in-c

// 有个回答
According to the C# language spec:

A foreach statement of the form

foreach (V v in x) embedded-statement

is then expanded to:

{
E e = ((C)(x)).GetEnumerator();
try {
V v;
while (e.MoveNext()) {
v = (V)(T)e.Current;
embedded-statement
}
}
finally {
... // Dispose e
}
}

The essense of your two examples are the same, but there are some important differences, most notably the try/finally.
vrhero 2009-02-28
  • 打赏
  • 举报
回复
如果仅是一个形参那么为什么会不允许修改
--------
不允许修改枚举项是foreach的特性,与var无关...

var是推断类型...由编译器根据初始化语句右侧的表达式推断变量的类型...

var关键字并不意味着“变体”,也不表示该变量是松散类型化变量或后期绑定变量。它只是表示由编译器确定和分配最适当的类型...

李睿_Lee 2009-02-28
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 king520520 的回复:]
foreach(一个人 in 一群人)
{
对每一个人进行操作
}

明白吗? 这属于迭代
[/Quote]
应该叫遍历吧?
wuyq11 2009-02-28
  • 打赏
  • 举报
回复
var关键字,在声明变量时就无需指定类型了,变量类型是在初始化时由编译器确定的。
whowhen21 2009-02-28
  • 打赏
  • 举报
回复
foreach 中那个参数是在后面的基础上的。也就是in 后面是什么类型的数据,她也必须是什么类型的,否则编译不通过!

因为只有相同类型了,才能判断是否在后面的集合或者数组之列!

你看看foreach的参数就知道了。in 后面必须是数组或者集合,反正不能是单独的个体。就着啦
king520520 2009-02-28
  • 打赏
  • 举报
回复
foreach(一个人 in 一群人)
{
对每一个人进行操作
}

明白吗? 这属于迭代
PandaIT 2009-02-28
  • 打赏
  • 举报
回复
var可以自定义的

liao5930 2009-02-28
  • 打赏
  • 举报
回复
var就是students中Keys集合的其中一项

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧