为什么foreach循环只读在C# [英] Why is foreach loop Read-Only in C#

查看:148
本文介绍了为什么foreach循环只读在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么foreach循环只读?我的意思是你可以获取数据,但不能增加++或decrease--。其背后的原因吗?
是的,我是一个初学者:)

Why is foreach loop a read only? I mean you can fetch the data but can't increase++ or decrease--. Any reason behind it? Yes I am a beginner :)

〔实施例:

int[] myArray={1,2,3};
foreach (int num in myArray)
{
  num+=1;
}


推荐答案

这是因为的foreach意指迭代一个容器,确保每个项被访问恰好一次,在不改变该容器,以避免讨厌的副作用。

That is because foreach is meant to iterate over a container, making sure each item is visited exactly once, without changing the container, to avoid nasty side effects.

请参阅:的foreach在MSDN

如果您的意思一样的整数不影响整数的容器为什么会改变为一个元素,以及这是因为迭代在这种情况下,该变量将是一个值的类型和被复制,例如:

If you meant why would changes to an element like an integer not affect a container of integers, well this is because the variable of iteration in this case would be a value type and is copied, e.g.:

// Warning: Does not compile
foreach (int i in ints)
{
  ++i; // Would not change the int in ints
}

即使迭代的变量是引用类型,其操作返回一个新的对象,则不会改变原始集合,也只是重新分配给该变量的大部分时间:

Even if the variable of iteration was a reference type, whose operations returned a new object, you wouldn't be changing the original collection, you would just be reassigning to this variable most of the time:

// Warning: Does not compile
foreach (MyClass ob in objs)
{
  ob=ob+ob; // Reassigning to local ob, not changing the one from the original 
            // collection of objs
}

下面的例子有实际调用修改原始集合中的对象的潜力的突变的方法:

// Warning: Does not compile
foreach (MyClass ob in objs)
{
  ob.ChangeMe(); // This could modify the object in the original collection
}

要避免就价值VS引用类型和上面提到的场景混乱(有涉及优化的一些原因一起),MS选择了把迭代变量只读

To avoid confusion with regard to value vs reference types and the scenarios mentioned above (along with some reasons related to optimization), MS chose to make the variable of iteration readonly.

这篇关于为什么foreach循环只读在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆