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

C# 每次使用时检查属性是否为null?,c#,.net,code-standards,C#,.net,Code Standards,我只是有一个简短的问题,看看在制作自己的课程时最好的做法是什么 假设这个类有一个在构造函数中初始化的私有成员,那么我是否需要检查这个私有成员在另一个公共的非静态方法中是否为null?或者假设变量不为null,因此不必添加该检查,这是否节省了时间 例如,如下所示,检查null是否绝对必要 // Provides Client connections. public TcpClient tcpSocket; /// <summary> /// Creates a telnet conn

我只是有一个简短的问题,看看在制作自己的课程时最好的做法是什么

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

谢谢。

您已经公开了该属性,因此使用该类的任何代码都可以将引用设置为null,从而导致对该类的任何操作都会引发null referenceexception

如果你想让你的类的用户生活在可防御的环境中:不,你不必检查null


您还可以将属性设置为public TcpClient tcpSocket{get;private set;},这样外部代码就不能将其设置为null。如果在类中未将tcpSocket设置为null,则它将永远不会为null,因为构造函数将始终被调用。

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


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

我不明白为什么您要在ctor中打开一个连接,然后使用public方法来关闭它。如果您正在ctor中创建连接,那么这通常意味着它是您希望在类的生命周期中使用的连接

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

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

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

在代码示例中,tcpSocket不是私有的。还有什么能阻止CloseSocket被多次调用?谢谢你的回复,你能看看我上面的编辑,看看这是否能更好地工作吗?谢谢