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

时间:2012-08-23 14:10:08

标签: c# .net code-standards

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

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

感谢。

3 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分:2)

我不明白为什么你在ctor中打开连接然后有公共方法来关闭它。如果您在ctor中创建连接,那么这通常意味着它是您在课堂生活中想要的连接。

如果您在询问如何确保在处理类时关闭连接,则实现IDisposable。

IDisposable Interface

因为它是私有的,所以它不应该为null,但你应该检查是否已连接。

   if (tcpSocket.Connected)
   {
       tcpSocket.Close();
   }

答案 2 :(得分:1)

通常,如果确保字段不为空,则是安全的。你可以把它称为类不变量。但是,在您的代码中,tcpSocket不是私密的,因此任何人都可以将其值设置为null

我建议您使用私有的setter将该字段设为属性(除非您可以将其完全设为私有)。这使您确保没有外部(即无法控制的!)代码修改引用。这反过来使您能够保证tcpSocket不是null