Obtaining an action goal

I created a code sample:

class Program { static void Main(string[] args) { var x = new ActionTestClass(); x.ActionTest(); var y = x.Act.Target; } } public class ActionTestClass { public Action Act; public void ActionTest() { this.Act = new Action(this.ActionMethod); } private void ActionMethod() { MessageBox.Show("This is a test."); } } 

When I do this along this path, y will be an object of type ActionTestClass (which is created for x). Now when i change the line

 this.Act = new Action(this.ActionMethod); 

to

 this.Act = new Action(() => MessageBox.Show("This is a test.")); 

y (Target of the Action) will be null. Is there a way that I can get the target (in the sample ActionTestClass object) also in the way of using an anonymous action?

+6
source share
3 answers

The absence of Target (iow == null ) implies that the delegate either calls the static method or no environment was captured (I do not close, just a "function pointer").

+1
source

You can use the following:

 Act.Method.DeclaringType 
0
source

the reason you see the target is empty because the anonymous method is not part of any class. If you open your program in a reflector, it will show you the code created by the compiler, here you will see the following

 public void ActionTest() { this.Act = delegate { Console.WriteLine("This is a test."); }; } 
0
source

Source: https://habr.com/ru/post/902570/


All Articles