我对这个c#代码有点混淆。这段代码来自http://trotinet.sourceforge.net/ 有人可以让我明白......
int port = 12345;
bool bUseIPv6 = false;
var Server = new TcpServer(port, bUseIPv6);
Server.Start(**TransparentProxy.CreateProxy**);
透明代理类:
public class TransparentProxy : ProxyLogic
{
public TransparentProxy(HttpSocket clientSocket)
: base(clientSocket)
{
}
static new public TransparentProxy CreateProxy(HttpSocket clientSocket)
{
return new TransparentProxy(clientSocket);
}
protected override void OnReceiveRequest()
{
Console.WriteLine("-> " + RequestLine + " from HTTP referer " +
RequestHeaders.Referer);
}
protected override void OnReceiveResponse()
{
Console.WriteLine("<- " + ResponseStatusLine +
" with HTTP Content-Length: " +
(ResponseHeaders.ContentLength ?? 0));
}
}
由于CreateProxy是带参数的静态方法,但是该方法是从没有参数的主程序调用的。这个示例应用程序工作正常,所以我有点困惑。所以,有人可以让我明白:)
谢谢!
答案 0 :(得分:1)
您的TcpServer.Start
方法将委托作为参数。
这意味着它只执行该方法,但稍后在Start
方法中执行。
这是Start
方法的签名(你可以在github上在线找到它):
public void Start(OnNewClient onConnection)
如您所见,OnNewClient
是代表:
public delegate AbstractProxyLogic OnNewClient(HttpSocket ss)
因此,此处的参数是一个与委托声明的签名具有相同签名的方法。
您可以在此处查看TcpServer
课程的源代码:
https://github.com/krys-g/TrotiNet/blob/master/Lib/TcpServer.cs
答案 1 :(得分:0)
TrotiNet.TcpServer类定义以下成员:
public delegate AbstractProxyLogic OnNewClient(HttpSocket ss);
public void Start(OnNewClient onConnection)
{
// ...
}
因此TcpServer.Start()方法采用委托参数。
方法TransparentProxy.CreateProxy()
匹配签名(TransparentProxy
继承自AbstractProxyLogic
),因此不会调用该方法,而是将其作为委托传递。