我有一些代码,当它执行时,它抛出一个NullReferenceException,说:
你调用的对象是空的.
这是什么意思,我该怎么做才能解决这个错误?
我有一个具有以下签名的异步方法:
public async Task UpdateMerchantAttributes(UpdateMerchantRequestModel model).
Run Code Online (Sandbox Code Playgroud)
该模型只有一个属性:
public Dictionary<string, string> Attributes { get; set; }
Run Code Online (Sandbox Code Playgroud)
有一段时间我用以下方式在测试中调用它:
await client.UpdateMerchantAttributes(new UpdateMerchantRequestModel { Attributes =
{
{"businessType", "0"}
}
});
Run Code Online (Sandbox Code Playgroud)
编译得很好,但NullReferenceException在该行上运行时引起了.我对此感到困惑,因为client它不是null,并且该行中没有引用任何其他内容(或者看起来一目了然).然后我尝试添加一个显式的Dictionary声明,如下所示:
await client.UpdateMerchantAttributes(new UpdateMerchantRequestModel { Attributes =
new Dictionary<string, string>
{
{"businessType", "0"}
}
});
Run Code Online (Sandbox Code Playgroud)
现在它传递得很好.这是我的错误,但如果这是一个编译错误而不是运行时空引用异常,那么这个错误将花费我更少的时间.所以我很好奇,为什么会这样呢?编译器是否认为我正在尝试定义一个dynamic并以某种方式解析为null?