是否可以在匿名函数中设置"this"?

mpe*_*pen 4 c# anonymous-function

我有一个功能,

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

其中为上下文的每个元素调用传入函数.是否可以设置"this"指的是什么内部Action<int, HtmlNode> function

例如,

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

Jef*_*ado 5

通过稍微改变功能,您可以获得所需的效果.

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

然后你可以像这样写你的函数调用:

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

注意:匿名函数只能访问公共成员.如果在类中定义了匿名函数,它将像往常一样访问受保护和私有成员.

例如,

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
Run Code Online (Sandbox Code Playgroud)