由于职能略有变化,你可以取得预期的效果。
public SharpQuery Each(Action<MyObject, int, HtmlNode> function)
{
for (int i = 0; i < _context.Count; ++i)
function(this, i, _context[i]);
return this;
}
接着,你可以照样写你的职责:
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.
例如,
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