Why anonymous methods inside structs can not access instance members of 'this'

后端 未结 2 924
广开言路
广开言路 2020-12-17 09:00

I have a code like the following:

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

    i         


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-17 09:39

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

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

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

    • The Truth About Value Types

    Note in response to the comment by Chris Sinclair:

    As a quick fix, you can store the struct in a local variable: A thisA = this; var items = Enumerable.Range(0, 10).Where(i => i == thisA._field); – Chris Sinclair 4 mins ago

    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.

提交回复
热议问题