我有一个函数,
public SharpQuery Each(Action<int, HtmlNode> function)
{
for (int i = 0; i < _context.Count; ++i)
function(i, _context[i]);
return this;
}
它为上下文的每个元素调用传入的函数。是否可以在 Action<int, HtmlNode> function
中设置“this”所指的内容? ?
例如,
sharpQuery.Each((i, node) => /* `this` refers to an HtmlNode here */);
最佳答案
稍微改变一下功能,就可以达到想要的效果。
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" */);
注意:匿名函数只能访问公共(public)成员。如果匿名函数是在类中定义的,它将像往常一样访问 protected 和私有(private)成员。
例如,
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
关于c# - 是否可以在匿名函数中设置 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4093642/