我们应该将变量设置为null,false并在初始化时创建新对象吗?

sil*_*lla 1 c# null

我在IBM页面上寻找.NET的一些filenet示例代码,我发现了这个:

namespace CESample
{
    // Represents the connection with the Content Engine.
    public class CEConnection
    {
        private IDomain domain;
        private IObjectStoreSet ost;
        private ArrayList osNames;
        private String domainName;
        private bool isCredentialsEstablished;

        // Constructor
        public CEConnection()
        {
            domain = null;
            ost = null;
            osNames = new ArrayList();
            domainName = null;
            isCredentialsEstablished = false;
        }

        //... other methods
Run Code Online (Sandbox Code Playgroud)

这没关系,在创建对象时始终将每个变量设置为null?那个bool和新的ArrayList()怎么样?那是我们应该怎么做的?将布尔值始终设置为false?

Dan*_*rth 6

除了数组列表之外的所有内容都是不需要的.

在执行构造函数内的代码之前,字段会使用各自的默认值自动初始化.

这段代码是等效的:

public class CEConnection 
{ 
    private IDomain domain; 
    private IObjectStoreSet ost; 
    private ArrayList osNames; 
    private String domainName; 
    private bool isCredentialsEstablished; 

    // Constructor 
    public CEConnection() 
    { 
        osNames = new ArrayList(); 
    } 
Run Code Online (Sandbox Code Playgroud)

  • @EamonNerbonne:我同意你评论的第一部分,但不同意最后一部分.明确可访问性是一个好主意. (2认同)