Interactive Brokers - EWrapperImpl 示例 - 对象引用未设置为对象的实例

Interactive Brokers - EWrapperImpl Example - Object reference not set to an instance of an object

为什么下面的代码在尝试使用 ClientSocket 时抛出对象引用错误?

我从 Interactive Brokers API 文档中复制了这个示例。

https://www.interactivebrokers.com/en/software/api/api.htm

我使用 IB 网关连接。

https://www.interactivebrokers.com/en/index.php?f=5041

我看到了下面的post,但是还是不清楚我这里哪里做错了

What is a NullReferenceException, and how do I fix it?

在 myClient.ClientSocket 行抛出错误:

var myClient = new EWrapperImpl();

myClient.ClientSocket.eConnect("127.0.0.1", 7496, 0);

这是包装器 class:

public class EWrapperImpl : EWrapper
{
    EClientSocket clientSocket;

    public EWrapperImpl()
    {
        clientSocket = new EClientSocket(this);
    }

    public EClientSocket ClientSocket { get; set; }
}

请注意,您在构造函数中初始化了 private 字段 clientSocket(使用小写 'c'),但访问 public 字段或 属性 ClientSocket(大写 'C')。 因此,您正在初始化一个从未使用过的字段,并尝试访问一个从未初始化过的 属性。

修复代码的最简单方法是删除私有字段并改为初始化 属性:

public class EWrapperImpl : EWrapper
{
    public EWrapperImpl()
    {
        ClientSocket = new EClientSocket(this);
    }

    public EClientSocket ClientSocket { get; set; }
}