自定义用户控件具有相同的方法,以相同的方式调用它们
因此,我在我的项目中制作了一堆用户控件,这些控件自动集成到系统中,以跟踪有关它们的某些内容。但我不确定如何做某个部分而不让它看起来很丑。
所有控件都从不同的控件类型(面板、文本框、组合框等)扩展而来,但具有几个完全相同的方法。
我想做的是避免这种情况:
public void SendMyMessage(Control thisControl)
{
if(thisControl is myPanel) (thisControl as myPanel).SendMessage();
else if(thisControl is myComboBox) (thisControl as myComboBox).SendMessage();
else if(thisControl is myTextbox) (thisControl as myTextbox).SendMessage();
else if(thisControl is myLabel) (thisControl as myLabel).SendMessage();
}
并且宁愿有一个更简单的方法,让我可以在一行中调用它。 (请注意,我调用的 SendMessage() 函数在不同的控件上执行不同的操作,但不需要参数并且以相同的方式调用)
So I have made a bunch of user controls in my project which integrate into a system automatically that tracks certain things about them. But I'm unsure on how to do a certain part without it looking really ugly.
All the Controls are extended from different Control types (Panel, Textbox, Combobox, etc) but have several of the exact same methods.
What I would like to do is avoid this:
public void SendMyMessage(Control thisControl)
{
if(thisControl is myPanel) (thisControl as myPanel).SendMessage();
else if(thisControl is myComboBox) (thisControl as myComboBox).SendMessage();
else if(thisControl is myTextbox) (thisControl as myTextbox).SendMessage();
else if(thisControl is myLabel) (thisControl as myLabel).SendMessage();
}
And would rather have a more simple method that would let me call that in 1 line. (Noting that the SendMessage() function I am calling does different things on different controls, but requires no arguments and is called the same way)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议在所有控件中实现类似
IMessageSender
接口的东西。所以你只能进行一项检查:界面如下所示:
I would suggest to implement something like
IMessageSender
interface in all your controls. So you can have only one check:where interface looks like this:
将消息放入接口中,并让所有控件实现该接口。
然后,您的方法可以直接使用该界面,并且可以与任何控件一起使用。
Put the message into an interface, and have all of the controls implement the interface.
Your method can then just use the interface directly, and will work with any of the controls.