function) { for (int i = 0...">

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

I have 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 function for each element of the context. Is it possible to establish what "this" means inside Action<int, HtmlNode> function ?

For instance,

 sharpQuery.Each((i, node) => /* `this` refers to an HtmlNode here */); 
+4
source share
2 answers

No.

Well, yes, if the Action was created in an area where 'this' was accessible and tied to closing, but transparently: no.

Pass all the necessary information or make sure that it is captured / available in the action itself. There are other hacks, such as threads, etc. Best avoided.

+1
source

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 can write your function call as follows:

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

Note. However, an anonymous function will only have access to public users. If an anonymous function was defined inside the class, it will have access to protected and private members, as usual.

eg.

 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 
+5
source

All Articles