我有一个简单的问题,想看看在制作自己的课程时最佳做法是什么。
假设这个类有一个在构造函数中初始化的私有成员,然后我是否必须检查这个私有成员在另一个公共的非静态方法中是否为空?或者假设变量不会为空,因此不必添加该检查是否可以保存?
例如,像下面这样,检查 null 是绝对必要的。
// Provides Client connections.
public TcpClient tcpSocket;
/// <summary>
/// Creates a telnet connection to the host and port provided.
/// </summary>
/// <param name="Hostname">The host to connect to. Generally, Localhost to connect to the Network API on the server itself.</param>
/// <param name="Port">Generally 23, for Telnet Connections.</param>
public TelnetConnection(string Hostname, int Port)
{
tcpSocket = new TcpClient(Hostname, Port);
}
/// <summary>
/// Closes the socket and disposes of the TcpClient.
/// </summary>
public void CloseSocket()
{
if (tcpSocket != null)
{
tcpSocket.Close();
}
}
因此,我根据您的所有答案进行了一些更改,我想知道这是否会更好:
private readonly TcpClient tcpSocket;
public TcpClient TcpSocket
{
get { return tcpSocket; }
}
int TimeOutMs = 100;
/// <summary>
/// Creates a telnet connection to the host and port provided.
/// </summary>
/// <param name="Hostname">The host to connect to. Generally, Localhost to connect to the Network API on the server itself.</param>
/// <param name="Port">TODO Generally 23, for Telnet Connections.</param>
public TelnetConnection(string Hostname, int Port)
{
tcpSocket = new TcpClient(Hostname, Port);
}
/// <summary>
/// Closes the socket and disposes of the TcpClient.
/// </summary>
public void CloseSocket()
{
if (tcpSocket != null)
{
tcpSocket.Close();
}
}
谢谢。