将委托分配给控件

时间:2015-03-11 14:46:31

标签: c# delegates

我正在尝试将方法绑定到按钮的click事件。

var controlEvent = button.GetType().GetEvent("Click");
var eventMethod = GetType().GetMethod("button_Click");
var handler = Delegate.CreateDelegate(controlEvent.EventHandlerType, button, eventMethod);

void button_Click(object sender, EventArgs e) { }

当我调用CreateDelegate时,我得到了

Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type

我觉得我将错误的类型传递给CreateDelegate,但我不确定。

2 个答案:

答案 0 :(得分:0)

这里没有理由使用反射。有一段时间以来,我一直使用winforms / webforms,但看起来应该是这样的:

button.OnClick += button_Click;

我进一步评论button_Click不是方法的好名字,除非它的作用是单击按钮。这个惯例来自一些非常古老的微软指导,而且它并不好。在他们做什么之后命名功能,而不是他们如何使用。考虑一下这个读取的好多了

button.OnClick += showCalculations;

我通常更进一步摆脱愚蠢的(object, EventArgs)参数(除非我使用这些参数)

button.OnClick += (o,e) => showCalculations();
//...
void showCalculations() {
   //...
}

答案 1 :(得分:0)

Delegate.CreateDelegate的第二个参数是调用方法的类实例。

您的方法未在button上定义,因此您收到错误 您需要通过this

相关问题