从数据库中检索方法名称,并将该方法用作委托 [英] Retrieving a method name from a DB and using that method as a delegate

查看:43
本文介绍了从数据库中检索方法名称,并将该方法用作委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个设置了委托方法的对象.我想要做的是存储一个方法名称(在数据库中说),然后将具有该名称的方法附加到对象的委托中.

我已经使用反射实现了这一点-示例代码如下:

Hi all,

I have an object with a delegate method set up. What I want to do is store a method name (in a database say), and then attach the method with that name to the object''s delegate.

I have achieved this using reflection - example code is below:

String ProgramName = "TestProgram";

ProgramClass MyObject = new ProgramClass();
MethodInfo ProgramInfo = MyObject.GetType().GetMethod(ProgramName);

Delegate del = Delegate.CreateDelegate(typeof(MyButton.ClickMethod), MyObject, ProgramInfo, false);

MyButton myButton = new MyButton();
myButton.Program = (MyButton.ClickMethod)del;



尽管确实有些慢,但这确实有效.本质上,我是动态产生一堆按钮,并且每个按钮都将附有一个程序",单击时会运行一种方法,但是该方法可以简单地编写一个字符(例如屏幕上的键盘)-因此,尽管此方法有效,但我确实需要更直接的响应.

有谁知道实现此目标的更好方法?使用委托不是最好的方法吗?

总结一下-我想将方法​​名称存储在数据库中,并在按下按钮时运行该方法.

非常感谢任何帮助.



This does work, though it appears to be a little on the slow side. Essentially, I''m dynamically producing a load of buttons, and each one will have a ''program'' attached to it, with is a method that is run when it is clicked - but this method can simply be to write a character (like an on-screen keyboard for example) - so although this method works, I need really a more immediate response.

Does anyone know of a better way to achieve this? Is the using a delegate not the best way?

To summarise - I''m wanting to store a method name in a database, and run that method when a button is pressed.

Any help greatly appreciated.

推荐答案

您无法避免使用反射,但是您可以考虑预先创建委托(例如,在应用启动时),保留这些委托在列表或字典中.稍后,您将使用此列表查找方法并附加已创建的委托.
You can not avoid using reflection, but you can consider creating your delegates in advance (for example when your app starts), keep those delegates in a list or a Dictionary. Later you use this list to lookup methods and attach already created delegate.


我不会在数据库中存储方法名称.我将存储一个(数字)指示符,该指示符告诉代码对委托使用哪种方法.这样,可以更改方法名称(如果需要/需要),并且数据库不需要(也不需要)知道它.
I wouldn''t store a method name in the database. I would store a (numeric) indicator that tells the code which method to use for the delegate. That way, the method name can be changed (if desired/required), and the database doesn''t need to (and shouldn''t need to) know about it.


这篇关于从数据库中检索方法名称,并将该方法用作委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆