2011-05-26 72 views
1

Im新的C#和框架林玩和我试图找出一些代码如何工作(没有什么错的代码)。它是一个客户端/服务器应用程序,它将一些文本从客户端发送到服务器,然后在文本框中接收并显示相同的字符串。 以下代码来自客户端及其表单。这里只包含从服务器接收字符串的东西。我收录了框架中的一些评论。帮助与代表解释代码

public class TestModuleMobile : PreCom.Core.ModuleBase, PreCom.Core.IForm 
{ 
    public delegate void ReceiveDelegate(string data); 
    public event ReceiveDelegate DataReceived; 

    public void Receive(byte[] data) 
    { 
     string text = Encoding.UTF8.GetString(data, 0, data.Length); 

     if (DataReceived != null) 
      DataReceived.Invoke(text); 
    } 

    public override bool Initialize() 
    { 
     PreCom.Application.Instance.Communication.Register(99, Receive);   
    // Register(uint receiverID, RecieveDelegate receiver): Called by modules to register for communication. 
    // 
    //  Parameters: 
    //   receiverID: 
    //    Module Id 
    //   receiver: 
    //    The module receive function that will be called by the framework when data 
    //    arrives to specific module. (This method should return as soon as possible 
    //    to avoid timeouts) 
     _isInitialized = true; 
     return true; 
    } 
} 

public partial class TestModuleMobileForm : PreCom.Controls.PreComForm 
{ 
    TestModuleMobile _module; 

    public TestModuleMobileForm(TestModuleMobile module) 
    { 
     _module = module; 
     _module.DataReceived += new TestModuleMobile.ReceiveDelegate(DataReceived); 
     InitializeComponent(); 
    } 

    void DataReceived(string data) 
    { 
     if (InvokeRequired) 
     { 
      ThreadStart myMethod = delegate { DataReceived(data); }; 
      this.BeginInvoke(myMethod); 
      return; 
     } 
     listBox1.Items.Insert(0, data); 
     this.preComInput21.Text = ""; 
    } 
} 

问题:
1.公共覆盖布尔初始化()
的函数调用来注册需要ReceiveDelegate对象作为第二个参数。那么当它只是一个函数时,我怎么能发送一个函数给它(Receive)呢?这个怎么用?

2. public void Receive(byte [] data)
if-case中会发生什么?如何调用工作?

3. void DataReceived(string data)
if-case(行一行)会发生什么?

+0

可能(甚至因为你是新来的.net)你应该得到一份[C#深入](http://www.amazon.com/dp/1935182471)的副本,并看看第2.5章快速跟踪的代表。 – Oliver 2011-05-26 10:03:38

回答

1

在Stackoverflow上有很多相关的帖子,您可以通过浏览来更好地了解代表。一旦你通读它们,重新审视你的代码,你会发现它更容易理解。

提示:点击此网页的右侧可查看所有相关帖子。