将事件处理函数VS压倒一切的大事,烧制方法 [英] Using event handlers vs overriding event-firing methods
问题描述
我创建按钮的子类,想自定义功能添加到它的一些事件,如onclick。这是更可取的办法做到这一点?难道我重写的OnClick:
I am creating a subclass of Button and would like to add custom functionality to some of its events such as OnClick. Which is the more desirable way to do it? Do I override OnClick:
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
doStuff();
}
或者我应该代替OnClick事件连接起来,通过设计在我的按钮子类中定义的事件处理程序?
or should I instead link up the OnClick event to an event handler defined in my Button subclass through the designer?
class ButtonSubclass
{
public ButtonSubclass() : base()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.Click += new System.EventHandler(this.ButtonSubclass_Click);
}
}
修改:我在加轻微的视觉变化(可能通过为基本的蒙皮),但大部分的变化是事件处理程序,我不想重新实现(复制粘贴)各种形式的重用它。
Edit: I added minor visual changes (that may pass as rudimentary skinning) but most of the changes are in event handlers that I don't want to re-implement (copy-paste) on every form that reuses it.
推荐答案
如果你是真正专业的按钮,是有意义的覆盖的OnClick
。如果你只的实际上的改变一个按钮被点击的时候,我就不会继承按钮
首先会发生什么 - 我倒是只是的添加事件处理程序。
If you're genuinely specializing the button, it makes sense to override OnClick
. If you're only actually changing what happens when a button is clicked, I wouldn't subclass Button
in the first place - I'd just add event handlers.
编辑:为了给多一点的想法 - 如果你想添加类似的事件处理程序多个按钮,它很容易编写一个实用的方法来做到这一点,并从多个地方调用它。它不需要实际子类。这并不是说子类的是的肯定是不对的,你的情况,当然 - 只是给你额外的选项:)
Just to give a bit more of an idea - if you want to add similar event handlers for multiple buttons, it's easy enough to write a utility method to do that, and call it from multiple places. It doesn't require actual subclassing. That's not to say subclass is definitely wrong in your case, of course - just giving you extra options :)
这篇关于将事件处理函数VS压倒一切的大事,烧制方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!