c#使用委托在表单和networkcommunicator类之间进行通信 [英] c# using delegates to communicate between forms and networkcommunicator class

查看:107
本文介绍了c#使用委托在表单和networkcommunicator类之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!



我正在尝试用c#开发一个应用程序,目前我的代码类似于下面的代码。

基本上它的作用是:

有多个表单,每个表单都希望使用我的NetworkCommunicator类的SendMessage方法通过网络发送消息。

我在这里描述的解决方案是有效的,但它很丑陋,并且打击了OOP范例的一些主要概念。

我正在寻找什么(我对任何建议持开放态度)基本上是为了实现相同的目标,但在更优雅,和OOP一致的解决方案。 (可能是活动?)



提前感谢您的回答,CB。



Ps。 :我使用的不仅仅是这些形式,但对于这个例子,这些似乎已经足够了。也请原谅我的英语,我不是母语人士。







Hello everyone!

I''m trying to develop an application in c# i currently have a code similar to the one attached below.
Basically what it does is:
Having multiple form, each of which would like to send message through the network, using my NetworkCommunicator class''s SendMessage method.
The solution i described here works, however it is ugly, and bludgeons some of the main concepts of OOP paradigm.
What I''m looking for (and i''m open to any suggestions) is basically to achieve the same goal but in a more elegant, and OOP conform solution. (maybe by events?)

Thank you for your answers in advance, CB.

Ps.: I''m using more than these forms, but for the example these seemed to be enough. Also excuse my english, I''m not a native speaker.



//using statements
namespace examplespace
{
  public delegate void ImprovedSenderDelegate(string message);  
 
  public class LoginForm :Form
   {
    private  NetworkCommunicator ncom = new NetworkCommunicator();
    public Ncom
    {
     get { return ncom; }
    }

    private void Login()
    {
     MainForm mf = new MainForm();
     mf.Owner = this;
     //other things i do etc.
     this.Hide();
     mf.Show();
    }      
   }//endofLoginForm
  
 public class MainForm :Form
 {
  public ImprovedSenderDelegate ISD;
  
  private Load ()
  {
   (this.Owner as LoginForm).NCom.SubscribeToSendMessage(this);
  }
  
  private void I_Want_To_send_A_Message(string message)
  {
   ISD(string);
  }
 }//endofMainForm
  
 public class NetworkCommunicator
  {
   public void SubscribeToSendMessage(object sender)
    {
     if (sender is MainForm)
     {
        
         (sender as MainForm).ISD += new ImprovedSenderDelegate(SendMessage);
     }
    }
  
   private void SendMessage(string message) 
    {/*magic*/}
  }/endofNetworkCommunicator
  
}    

推荐答案

你可以''通过网络做任何事情,因为你有两个不同的前任。你不能在两台机器上的两个前任之间使用代表。
You can''t do anything OO over the network, because you have two different exes running. You can''t use delegates between two exes on two machines.


这篇关于c#使用委托在表单和networkcommunicator类之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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