是否可以将“这个”设置为在匿名函数中?
我有一个函数,
public SharpQuery Each(Action<int, HtmlNode> function)
{
for (int i = 0; i < _context.Count; ++i)
function(i, _context[i]);
return this;
}
它为上下文的每个元素调用传入的函数。是否可以在 Action
例如,
sharpQuery.Each((i, node) => /* `this` refers to an HtmlNode here */);
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 */);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
稍微改变一下功能,就可以达到想要的效果。
然后您可以像这样编写函数调用:
注意:但是,匿名函数只能访问公共成员。如果匿名函数是在类中定义的,则它将像往常一样访问受保护的成员和私有成员。
例如,
With a slight change in the function, you can achieve the desired effect.
Then you could write your function call like so:
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.,
不。
嗯,是的,如果 Action 是在“this”可用并绑定在闭包中的范围内创建的,但显然:不。
传递所有需要的信息或确保它在操作本身中捕获/可用。还有其他黑客,如线程局部变量等。最好避免。
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.