开发者

Is it possible to set "this" in anonymous function?

I've got a function,

public SharpQuery Each(Action<int, HtmlNode> function)
开发者_运维百科{
    for (int i = 0; i < _context.Count; ++i)
        function(i, _context[i]);
    return this;
}

Which calls the passed in function for each element of the context. Is it possible to set what "this" refers to inside Action<int, HtmlNode> function?

For example,

sharpQuery.Each((i, node) => /* `this` refers to an HtmlNode here */);


With a slight change in the function, you can achieve the desired effect.

public SharpQuery Each(Action<MyObject, int, HtmlNode> function)
{
    for (int i = 0; i < _context.Count; ++i)
        function(this, i, _context[i]);
    return this;
}

Then you could write your function call like so:

sharpQuery.Each((self, i, node) => /* do something with `self` which is "this" */);

Note: The anonymous function will only have access to public members however. If the anonymous function was defined within the class, it will have access to protected and private members as usual.

e.g.,

class MyObject
{
    public MyObject(int i)
    {
        this.Number = i;
    }

    public int Number { get; private set; }
    private int NumberPlus { get { return Number + 1; } }

    public void DoAction(Action<MyObject> action)
    {
        action(this);
    }

    public void PrintNumberPlus()
    {
        DoAction(self => Console.WriteLine(self.NumberPlus));  // has access to private `NumberPlus`
    }
}

MyObject obj = new MyObject(20);
obj.DoAction(self => Console.WriteLine(self.Number));     // ok
obj.PrintNumberPlus();                                    // ok
obj.DoAction(self => Console.WriteLine(self.NumberPlus)); // error


No.

Well, yes, if the Action was created in such a scope where 'this' was available and bound in a closure -- but transparently: no.

Pass in all needed information or make sure it's captured/available in the Action itself. There are other hacks like thread-locals, etc. Best avoided.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜