如果我有:
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,强调我的:
The type and identifier of a foreach statement declare the iteration variable of the statement.
The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement.
During execution of a foreach statement, the iteration variable represents the collection element for which an iteration is currently being performed.
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/