Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this as one of my members of the class 'KeyEvent':

private delegate void eventmethod();

And the constructor:

public KeyEvent(eventmethod D) 
{
    D();
}

What I want to do is instead of calling D() there, I want to store that method (D) as a member variable of KeyEvent, so something like:

stored_method = D();

And then later in another method of KeyEvent, do something like:

stored_method();

How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
156 views
Welcome To Ask or Share your Answers For Others

1 Answer

You pretty much have the code already. Just create a member field of the right delegate type and save the parameter to it just like you would with any other data type.

private eventmethod MySavedEvent;

public void KeyEvent(eventmethod D) {
    // Save the delegate
    MySavedEvent = D;
}

public void CallSavedEvent() {
    if (MySavedEvent != null) {
        MySavedEvent();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...