加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 只读本地变量不能用作赋值对象

发布时间:2020-12-15 17:46:08 所属栏目:百科 来源:网络整理
导读:如果我有: var myObjects = new ConcurrentBagobject(); 并尝试通过以下方式删除对象: foreach (var myObject in myObjects.ToArray()){ myObjects.TryTake(out myObject);} 编译器抱怨:“只读本地变量不能用作赋值目标” 然而,如果我在foreach中添加一个
如果我有:
var myObjects = new ConcurrentBag<object>();

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

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

编译器抱怨:“只读本地变量不能用作赋值目标”

然而,如果我在foreach中添加一个本地引用,它会编译:

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

这里究竟发生了什么?

解决方法

foreach中的迭代变量(即myObject)不能在foreach内部分配一个新值.不允许.

在第一种情况下,外部尝试这样做.在第二种情况下,你永远不会尝试重新分配给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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读