c# - 每次使用时检查属性是否为空?

标签 c# .net code-standards

我有一个简短的问题,想知道在您自己上课时最佳做法是什么。

假设这个类有一个在构造函数中初始化的私有(private)成员,我是否必须在另一个公共(public)的非静态方法中检查这个私有(private)成员是否为空?还是假设变量不会为空,因此不必添加该检查?

例如,如下所示,是否绝对需要检查 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();
    }  
}

谢谢。

最佳答案

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

如果您希望您类(class)的用户接受它(这是可以防御的):不,您不必检查 null。

你也可以使属性像public TcpClient tcpSocket { get;私有(private)集; },因此外部代码无法将其设置为空。如果您不在您的类中tcpSocket 设置为 null,它将永远不会为 null,因为构造函数将始终被调用。

关于c# - 每次使用时检查属性是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12093599/

相关文章:

C# 泛型函数

c# - 优势 错误 6082

c# - 从用户输入中读取一个整数

c# - 是否有可能有一个取消 token 源,仅取消一些服务员?

java - 抑制 suppressions.xml 中 PRIVATE 成员变量的 checkstyle 错误?

qa - 编码标准在防止错误(在医疗应用程序中)的影响的证据?

c# - 版本控制 API 端点

c# - C#中字符串前面的@是什么?

c# - 重定向到错误页面

php - 最佳实践 : returning multiple values