将方法存储为类的成员变量
我将此作为“KeyEvent”类的成员之一:
private delegate void eventmethod();
构造函数:
public KeyEvent(eventmethod D)
{
D();
}
我想要做的是不在那里调用 D(),而是将该方法 (D) 存储为 KeyEvent 的成员变量,因此类似:
stored_method = D();
然后在 KeyEvent 的另一个方法中,执行类似以下操作:
stored_method();
我怎样才能做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您几乎已经有了代码。只需创建正确委托类型的成员字段并将参数保存到其中,就像使用任何其他数据类型一样。
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.
您可以执行以下操作:
可以通过以下方式实例化:
其中 MyFunction 是该类中某个函数的名称
KeyEvent 类可以使用以下方式调用该函数:
Action 类还允许传入强类型参数,并且 Func 类可以用于返回结果的方法。
You could do something like:
Which can be instantiated by:
Where MyFunction is the name of some function in that class
The KeyEvent class can then invoke that function with:
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.
你想要的东西叫做“第一类函数” http://en.wikipedia.org/ wiki/First-class_function
C# 从版本 3 开始,支持匿名函数和 lambda 表达式。
返回 R 类型的值
因此,您可以使用
Func
表示一个函数,该函数采用 A 类型的参数并从 wikithe 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 Rfrom wiki
一些事情...... PascalCase 类型/委托/等(EventMethod)和camelCase 参数(d,dIsMyMethod)。并重用框架为您提供的内容:
private Action hurr;
Couple things... PascalCase types/delegates/etc (EventMethod) and camelCase arguments (d, dIsMyMethod). And reuse what the framework gives you:
private Action hurr;