说我有以下代码:
public static Client Connect(string hostname, int port, bool useSsl)
{
TcpClient tcpClient = new TcpClient(hostname, port);
if (!useSsl)
{
return new Client(tcpClient.GetStream());
}
SslStream sslStream = new SslStream(tcpClient.GetStream());
sslStream.AuthenticateAsClient(hostname);
return new Client(sslStream);
}
当我编译它时,Code Analysis告诉我在引用超出范围之前我应该处理tcpClient
。问题是我需要进一步使用底层流实例,我不能在这里处理tcpClient
。同时,我不想在某处存储对tcpClient
的引用,以便稍后处理,因为我只需要流。这里的解决方案是什么?感谢。
答案 0 :(得分:1)
public class Client : IDisposable
{
private TcpClient tcpClient = null;
public Client(string hostname, int port, bool useSsl) // c'tor
{
tcpClient = new TcpClient(hostname, port);
if (!useSsl)
{
Init(tcpClient.GetStream());
return;
}
SslStream sslStream = new SslStream(tcpClient.GetStream());
sslStream.AuthenticateAsClient(hostname);
Init(sslStream);
}
private void Init(Stream stream)
{
// bla bla bla
}
public void Dispose()
{
// this implementation of Dispose is potentially faulty (it is for illustrative purposes only)
// http://msdn.microsoft.com/en-us/library/ms244737%28v=vs.80%29.aspx
if( tcpClient != null ) {
tcpClient.Close();
tcpClient = null;
}
}
}
答案 1 :(得分:0)
你可以通过两种方式实现这一目标。 1.通过ref或传递var 2.在顶部声明一个私有变量 SslStream sslStream = null; 有这个
SslStream sslStream = new SslStream(tcpClient.GetStream());
将其或方法更改为以下内容。
public static SSLStream Connect(ref string hostname, ref int port, bool useSsl)
{
TcpClient tcpClient = new TcpClient(hostname, port);
if (!useSsl)
{
return new Client(tcpClient.GetStream());
}
sslStream = new SslStream(tcpClient.GetStream()); // or the ref sslStream
sslStream.AuthenticateAsClient(hostname);
tcpClient = null; or if implements IDisposable then do this
if (tcpClient != null)
{
((IDisposable)tcpClient).Dispose();
}
return sslStream; //if yo
}