6

I have created the fallowing Sample-Code:

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 on this way, y will 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 (the Target of the Action) will be null. Is there a way, that I can get the Target (in the sample the ActionTestClass-object) also on the way I use an Anonymous Action?

BennoDual
  • 5,865
  • 15
  • 67
  • 153
  • Personally I'm not surprised that that `Action` doesn't know anything about the `ActionTestClass` that refers to it. Why would it? – AakashM Nov 28 '11 at 15:58
  • @AakashM: In the first example you are binding to an instance method, so `Target` needs to be not null. This however might not fail due to no usage of any instance variables. I dont think you can bind it without a `Target` using a delegate constructor though. – leppie Nov 28 '11 at 16:25
  • @leppie sorry, I meant the second example - unlike the first example, for the second `Action` it is clear by inspection that it has nothing to do with any particular object, so I'm not at all surprised that its `Target` is `null`. Should I be expecting something else? – AakashM Nov 28 '11 at 16:38

3 Answers3

1

The lack of Target (iow == null) implies the delegate is either calling a static method or no environment has been captured (iow not a closure, just a 'function pointer').

leppie
  • 115,091
  • 17
  • 196
  • 297
  • 1
    Exercise to reader: Understand why closures are the poor man's classes with regards to the answer above. – leppie Nov 28 '11 at 15:27
0

You can use the following:

Act.Method.DeclaringType
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
0

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

public void ActionTest()
    {
        this.Act = delegate {
            Console.WriteLine("This is a test.");
        };
    }
np-hard
  • 5,725
  • 6
  • 52
  • 76