gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:33:22 24 4
gpt4 key购买 nike

如果我有:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com