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

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

问题描述

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

示例:

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

解决方案

那是因为 foreach 旨在迭代一个容器,确保每个项目只被访问一次,而无需更改容器,以避免令人讨厌的副作用.

请参阅:MSDN 中的foreach

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

//警告:不编译foreach (int i in int){++i;//不会改变 ints 中的 int}

即使迭代的变量是一个引用类型,其操作返回一个新对象,你也不会改变原始集合,你只会在大多数情况下重新分配给这个变量:

//警告:不编译foreach(对象中的MyClass ob){ob=ob+ob;//重新分配给本地ob,不改变原来的ob//对象集合}

以下示例有可能通过调用 mutating 方法实际修改原始集合中的对象:

//警告:不编译foreach(对象中的MyClass ob){ob.ChangeMe();//这可以修改原始集合中的对象}

为了避免在值与引用类型以及上述场景(以及与优化相关的一些原因)方面的混淆,MS 选择将迭代变量设为 readonly.

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 :)

Exmaple:

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

解决方案

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.

See: foreach in 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
}

The following example has the potential to actually modify the object in the original collection by calling a mutating method:

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

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天全站免登陆