我有一个用于通过TCP/IP建模外部设备的类。这个类创建了一个客户端,基本上是System.Net.Sockets.TcpClient的包装器。应用程序类持有这个类的实例。
根据https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose#cascade-dispose-calls,如果一个类拥有一个实现IDisposable的字段,那么它也应该实现IDisposable。
因此,在我的情况下,TcpClient实现了IDisposable,因此我的客户端类必须实现IDisposable,因此我的外部设备类必须实现IDisposable,因此我的应用程序类必须实现IDisposable。
听起来很麻烦,所以我在质疑这样做是否正确?
public class Client : IDisposable
{
private TcpClient _tcpClient;
...
public void Connect()
{
_tcpClient = new TcpClient();
if (!_tcpClient.ConnectAsync(address, port).Wait(1000))
...
}
public void Disconnect()
{
_tcpClient?.Dispose();
_tcpClient = null;
}
#region IDisposable
...
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_tcpClient?.Dispose();
_tcpClient = null;
}
_disposed = true;
}
#endregion
...
}
public class SM15k : IDisposable
{
private readonly Client _client;
...
public SM15k()
{
_client = new Client();
}
#region IDisposable
...
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_client.Dispose();
}
_disposed = true;
}
#endregion
...
}
public class App : IDisposable
{
private SM15k _SM15k;
#region IDisposable
...
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_SM15k?.Dispose();
_SM15k = null;
}
_disposed = true;
}
#endregion
...
}