每次使用时检查属性是否为null?

Fey*_*ity 4 .net c# code-standards

我只是有一个简单的问题,看看自己上课时最好的做法是什么.

假设这个类有一个私有成员在构造函数中初始化,我是否必须检查这个私有成员在另一个公共的非静态方法中是否为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();
    }  
}
Run Code Online (Sandbox Code Playgroud)

所以,我根据你的所有答案做了一些改变,我想知道这是否会更好:

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();
    }  
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Cod*_*ter 6

您已将该属性设置为public,因此使用此类的任何代码都可以将引用设置为null,从而导致对其执行任何操作以抛出NullReferenceException.

如果你希望你的班级用户(可以辩护):不,你不必检查null.

您也可以将属性public TcpClient tcpSocket { get; private set; }设置为,因此外部代码不能将其设置为null.如果你没有 类中设置tcpSocket为null ,它将永远不会为null,因为将始终调用构造函数.