简体   繁体   English

将方法存储为类的成员变量

[英]Storing a method as a member variable of a class

I have this as one of my members of the class 'KeyEvent': 我把它作为我的'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: 我想要做的不是在那里调用D(),我想将该方法(D)存储为KeyEvent的成员变量,所以类似于:

stored_method = D();

And then later in another method of KeyEvent, do something like: 然后在另一个KeyEvent方法中,执行以下操作:

stored_method();

How can I do this? 我怎样才能做到这一点?

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

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 其中MyFunction是该类中某些函数的名称

The KeyEvent class can then invoke that function with: 然后,KeyEvent类可以使用以下命令调用该函数:

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. Action类还允许传入强类型参数,Func类可用于返回结果的方法。

the thing that you want is called "first class function" http://en.wikipedia.org/wiki/First-class_function 你想要的东西叫做“头等功能” http://en.wikipedia.org/wiki/First-class_function

C#, since version 3, supports anonymous functions and lambda expressions. 从版本3开始,C#支持匿名函数和lambda表达式。

So you can use Func<A,R> which represents a function taking an argument of type A and returning a value of type R 因此,您可以使用Func<A,R>表示采用类型A的参数并返回类型R的值的函数

from wiki 来自维基

static Func<double, double> MakeDerivative(Func<double, double> f, double deltaX)
  {
    return (x) => (f(x + deltaX) - f(x - deltaX)) / (2 * deltaX);
  }
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). 几件事...... PascalCase类型/委托/ etc(EventMethod)和camelCase参数(d,dIsMyMethod)。 And reuse what the framework gives you: private Action hurr; 并重用框架为您提供的内容: private Action hurr;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM