实例化变量不包含任何值

Instantiated variable does not contain any value

我有一个叫 ClassModel 的 class。这是它的样子。

class ClassModel
{
    dynamic ConnListInstance;

    public ClassModel() {
        ConnListInstance = Activator.CreateInstance(Type.GetTypeFromProgID("PCOMM.autECLConnlist"));
    }

    public void checkCount() { //this shows a count of 0
        Console.WriteLine(ConnListInstance.Count());
    }

    public void checkCountVersionTwo() { //this shows a count of 1
        ConnListInstance = Activator.CreateInstance(Type.GetTypeFromProgID("PCOMM.autECLConnlist"));
        Console.WriteLine(ConnListInstance.Count());
    }
}

我通过声明 ClassModel obj = new ClassModel() 在我的主页中实例化了 class。

但是当我尝试调用 checkCount 方法时,它 returns 0 而不是 1。 checkCountVersionTwo returns 1 但只是因为我添加了实例化构造函数。

我创建构造函数和 class 的方式有问题吗?我可以知道它为什么返回 null/empty 值吗?在创建新的 ClassModel 对象时,变量 ConnListInstance 不应该有值吗?

这与您的代码无关,但原因在于此对象的工作方式。

请阅读documentation:

An autECLConnList object provides a static snapshot of current connections. The list is not dynamically updated as connections are started and stopped. The Refresh method is automatically called upon construction of the autECLConnList object. If you use the autECLConnList object right after its construction, your list of connections is current. However, you should call the Refresh method in the autECLConnList object before accessing its other methods if some time has passed since its construction to ensure that you have current data. Once you have called Refresh you may begin walking through the collection

(强调我的)

所以解决方案是:

public void checkCount() 
{
    ConnListInstance.Refresh();
    Console.WriteLine(ConnListInstance.Count());
}

这是没有任何其他操作的完整代码吗?

广告据此,以下似乎是这种情况。请添加进一步的代码来澄清。

  1. 在构造函数中,您将拥有一个有效实例,除非 CreateInstance 由于某种原因失败

  2. 在第一种检查方法中,您将获得它拥有的任何实体的计数(从构造时间到方法调用时间)。

  3. 在第二种检查方法中,您正在重新创建对象并再次在同一块中检索其计数。因此,将实体添加到列表的任何可能时间都在 ConnListInstance.

  4. 的构造函数内

因此,对于 #2,您似乎正在操纵所包含的基础数据,因此列表计数报告为 0;而在新建时,报告为 1。