Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

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

I have a code like the following:

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

    int _field;
}

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

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

Can anybody explains what's going on here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...