Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

c# - Storing a method as a member variable of a class

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

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

1 Reply

0 votes
by (71.8m points)

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...