独自のクラスを作成する際のベスト プラクティスを確認するための簡単な質問があります。
このクラスに、コンストラクターで初期化されるプライベート メンバーが 1 つあるとします。次に、このプライベート メンバーが別の非静的メソッドで null かどうかを確認する必要がありますか? それとも、変数がnullにならないため、そのチェックを追加する必要がないと仮定するのは保存されていますか?
例えば以下のように、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();
}
}
ありがとう。