为什么结构中的匿名方法无法访问"this"的实例成员 [英] Why anonymous methods inside structs can not access instance members of 'this'

查看:45
本文介绍了为什么结构中的匿名方法无法访问"this"的实例成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下代码:

struct A
{
    void SomeMethod()
    {
        var items = Enumerable.Range(0, 10).Where(i => i == _field);
    }

    int _field;
}

...然后出现以下编译器错误:

... and then i get the following compiler error:

结构内部的匿名方法无法访问'this'的实例成员.

Anonymous methods inside structs can not access instance members of 'this'.

任何人都可以解释这里发生的事情.

Can anybody explains what's going on here.

推荐答案

变量通过引用捕获(即使它们实际上是值类型;也可以进行装箱).

Variables are captured by reference (even if they were actually value-types; boxing is done then).

但是,不能将ValueType(结构)中的 this 装箱,因此无法捕获它.

However, this in a ValueType (struct) cannot be boxed, and hence you cannot capture it.

Eric Lippert上有一篇不错的文章,介绍了捕获ValueType的惊喜.让我找到链接

Eric Lippert has a nice article on the surprises of capturing ValueTypes. Let me find the link

请注意对克里斯·辛克莱尔的评论:

Note in response to the comment by Chris Sinclair:

作为快速解决方案,您可以将结构存储在本地变量中: A thisA = this;var items = Enumerable.Range(0,10).Where(i => i == thisA._field); 4分钟前

请注意,这会产生令人惊讶的情况: thisA identity this 不相同>.更明确地说,如果您选择将 lambda 保留更长的时间,则会通过引用捕获带框的副本 thisA ,而调用了 SomeMethod 的实际实例.

Beware of the fact that this creates surprising situations: the identity of thisA is not the same as this. More explicitly, if you choose to keep the lambda around longer, it will have the boxed copy thisA captured by reference, and not the actual instance that SomeMethod was called on.

这篇关于为什么结构中的匿名方法无法访问"this"的实例成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆