相关疑难解决方法(0)

什么是NullReferenceException,我该如何解决?

我有一些代码,当它执行时,它抛出一个NullReferenceException,说:

你调用的对象是空的.

这是什么意思,我该怎么做才能解决这个错误?

.net c# vb.net null nullreferenceexception

1876
推荐指数
24
解决办法
127万
查看次数

为什么在字典中使用隐式集合初始化程序会导致C#中的运行时错误?

我有一个具有以下签名的异步方法:

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

c#

2
推荐指数
1
解决办法
90
查看次数

标签 统计

c# ×2

.net ×1

null ×1

nullreferenceexception ×1

vb.net ×1