繁体   English   中英

了解代表和回调

[英]Understanding Delegates & Callbacks

在Unity项目中使用此C#TCP Server示例

https://www.codeproject.com/articles/488668/csharp-tcp-server

提到的注释有3个回调事件OnConnect,OnDataAvailable和OnError。 有2个具有以下签名的回调示例

private void tcpServer1_OnDataAvailable(tcpServer.TcpServerConnection connection)

我是否需要执行任何特殊操作或者除了启用这些回调之外还是tcpServer1_OnDataAvailable是否包含自动调用的保留处理程序名称?

TcpServer tcpServer1 = new TcpServer(); //in constructor (auto added if added as a component)

private void openTcpPort(int port)
{ 
    tcpServer1.Port = port;
    tcpServer1.Open();
}

private void closeTcpPort()
{
    tcpServer1.Close();
}  

您需要将事件处理程序委托注册到特定事件。

TcpServer tcpServer1 = new TcpServer(); 

// register event handler
tcpServer1.OnDataAvailable += tcpServer1_OnDataAvailable;


private void tcpServer1_OnDataAvailable(tcpServer.TcpServerConnection connection)
{
  // do work
}

回调是在您感兴趣的事件发生时调用的方法。 你确实需要设置它们,如下所示:

tcpServer1.OnConnect += serverConnection => 
{
   //code to do stuff when a connection happens goes here
}

tcpServer1.OnDataAvailable += serverConnection =>
{
  //code to do stuff when data is available here
}

tcpServer1.OnError += serverConnection => 
{
   //code to do stuff when an error happens here
}

在使用operator new实例化tcpServer1的变量的时间点之后,您应该将此代码放在构造函数中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM