自定义用户控件具有相同的方法,以相同的方式调用它们

发布于 2024-12-21 13:28:14 字数 629 浏览 2 评论 0原文

因此,我在我的项目中制作了一堆用户控件,这些控件自动集成到系统中,以跟踪有关它们的某些内容。但我不确定如何做某个部分而不让它看起来很丑。

所有控件都从不同的控件类型(面板、文本框、组合框等)扩展而来,但具有几个完全相同的方法。

我想做的是避免这种情况:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千仐 2024-12-28 13:28:14

我建议在所有控件中实现类似 IMessageSender 接口的东西。所以你只能进行一项检查:

if (thisControl is IMessageSender)
  (thisControl as IMessageSender).SendMessage();

界面如下所示:

public interface IMessageSender
{
  void SendMessage();
}

I would suggest to implement something like IMessageSender interface in all your controls. So you can have only one check:

if (thisControl is IMessageSender)
  (thisControl as IMessageSender).SendMessage();

where interface looks like this:

public interface IMessageSender
{
  void SendMessage();
}
逆光下的微笑 2024-12-28 13:28:14

将消息放入接口中,并让所有控件实现该接口。

然后,您的方法可以直接使用该界面,并且可以与任何控件一起使用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文