在 C# 中初始化没有值的字典

use*_*890 3 c# dictionary

我想创建仅包含键的字典。例如:

Dictionary <string, double> SmplDict= new Dictionary<string, double>();
SmplDict.Add("KeyOne");
SmplDict.Add("KeyTwo");
Run Code Online (Sandbox Code Playgroud)

当然,我可以使用一些预定义值进行初始化,但这些值将被覆盖,因此我现在只想声明键。我试过

SmpDict.Add("KeyOne", null)
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

Yai*_*vet 5

您不能将null值放在预期值的位置double,因为它不是引用类型而是值类型:

Dictionary <string, double>
Run Code Online (Sandbox Code Playgroud)

相反,输入0

SmpDict.Add("KeyOne", 0)
Run Code Online (Sandbox Code Playgroud)

另一方面,如果您想保留 put null,请将您的double值标记为可为空:

Dictionary <string, double?>
Run Code Online (Sandbox Code Playgroud)