c# - 只读局部变量不能用作赋值目标

标签 c#

如果我有:

var myObjects = new ConcurrentBag<object>();

并尝试通过以下方式删除对象:

foreach (var myObject in myObjects.ToArray())
{
    myObjects.TryTake(out myObject);
}

编译器提示:“Readonly local variable cannot be used as an assignment target”

但是,如果我在 foreach 中添加本地引用,它会编译:

foreach (var myObject in myObjects.ToArray())
{
    var localReference = myObject;
    myObjects.TryTake(out localReference);
}

这里到底发生了什么?

最佳答案

foreach 中的迭代变量(即 myObject)不能foreach 中分配新值.这是不允许的。

在第一种情况下,out 尝试这样做。在第二种情况下,您*永远不会尝试重新分配给 myObject,所以没问题。

引用 ECMA 规范 15.8.4,强调我的:

  1. The type and identifier of a foreach statement declare the iteration variable of the statement.

  2. The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement.

  3. During execution of a foreach statement, the iteration variable represents the collection element for which an iteration is currently being performed.

  4. A compile-time error occurs if the embedded statement attempts to modify the iteration variable (via assignment or the ++ and --operators) or pass the iteration variable as a ref or out parameter.

关于c# - 只读局部变量不能用作赋值目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11251855/

相关文章:

c# - 使用 C# 和 symantec 扫描引擎进行病毒扫描

c# - 不使用闰年函数计算闰年

c# - 在一个应用程序窗口中显示其他应用程序的实时屏幕

c# - 大智能 ViewModels、愚蠢的 Views 和任何模型,最好的 MVVM 方法?

c# - 自定义上下文菜单

c# - 使用 Linq to sql 概念的 wpf 更新记录中的问题

c# - 在 SQL Server 中最后更新记录时保存

c# - 如何在 XAML 中处理 "float"图像 (Windows 8 Metro)

c# - 使用 LINQ。有两个不同的列表。如何识别不匹配的对象

c# - 在asp.net中使用jquery做一些ajax