Storing a method as a member variable of a class

后端 未结 4 498
野趣味
野趣味 2020-12-11 14:58

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

private delegate void eventmethod();

And the constructor:

publi         


        
相关标签:
4条回答
  • 2020-12-11 15:28
    public class KeyEvent
    {
      private eventmethod hurr;
      public KeyEvent(eventmethod D)
      {
        hurr = D;
      }
      public void SomeOtherMethod()
      {
        hurr();
      }
    }
    

    Couple things... PascalCase types/delegates/etc (EventMethod) and camelCase arguments (d, dIsMyMethod). And reuse what the framework gives you: private Action hurr;

    0 讨论(0)
  • 2020-12-11 15:32

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-11 15:35

    the thing that you want is called "first class function" http://en.wikipedia.org/wiki/First-class_function

    C#, since version 3, supports anonymous functions and lambda expressions.

    So you can use Func<A,R> which represents a function taking an argument of type A and returning a value of type R

    from wiki

    static Func<double, double> MakeDerivative(Func<double, double> f, double deltaX)
      {
        return (x) => (f(x + deltaX) - f(x - deltaX)) / (2 * deltaX);
      }
    
    0 讨论(0)
  • 2020-12-11 15:52

    You could do something like:

    private Action CallBackFunction {get; set;}
    
    public KeyEvent(Action callback) {
       CallBackFunction = callback;
    }
    

    Which can be instantiated by:

    new KeyEvent(MyFunction);
    

    Where MyFunction is the name of some function in that class

    The KeyEvent class can then invoke that function with:

    CallBackFunction();
    

    The Action class also allows strongly typed parameters to be passed in and the Func class can be used for methods that return a result.

    0 讨论(0)
提交回复
热议问题