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

Jan*_*sky 2 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

mjw*_*lls 7

第一种形式:

Attributes = 
    {
        {"businessType", "0"}
    }
}
Run Code Online (Sandbox Code Playgroud)

语法糖.Add(key, value).就这些.它不关心创建字典(因此,实际上,您正在添加到null字典中).

你的第二种形式是解决它的一种方式.另一种更加防弹的方式(因为它可以保护你免受第一种形式的影响),就是使用@ MarcGravell的建议:

public Dictionary<string, string> Attributes
    { get; } = new Dictionary<string,string>(); // set; after the get; is also OK
Run Code Online (Sandbox Code Playgroud)

或者Attributes在构造函数中填充.