我正在尝试使用程序的一些硬编码参考信息创建一个静态类。该静态类包含一个枚举和一个参考字典,该字典使用该枚举选择一组预定义的数值。这是我在下面做什么的示例:
enum CellChemistry
{
PbAc,
NiZn,
NiMH
}
public static class ChemistryInfo
{
public static readonly Dictionary<CellChemistry, decimal> NominalVoltage = new Dictionary<CellChemistry, decimal>
{
{ CellChemistry.PbAc, 2 },
{ CellChemistry.NiZn, 1.7 },
{ CellChemistry.NiMH, 1.2 }
};
}
但是,我不断收到这样的语法错误:{ CellChemistry.PbAc, 2 },
初始化字典说:
The Best overloaded Add method 'Dictionary<CellChemistry, decimal>.Add(CellChemistry, decimal)' for the collection initializer has some invalid arguments.
这是什么意思,我该如何解决?
问题是没有从double
到的隐式转换decimal
。如果您尝试仅将值分配给变量,则可以看到以下内容:
decimal x1 = 2; // Fine, implicit conversion from int to decimal
decimal x2 = 1.7; // Compile-time error, no implicit conversion from double to decimal
decimal x3 = 1.2; // Compile-time error, no implicit conversion from double to decimal
您想改用十进制文字-使用m
后缀:
public static readonly Dictionary<CellChemistry, decimal> NominalVoltage = new Dictionary<CellChemistry, decimal>
{
{ CellChemistry.PbAc, 2 },
{ CellChemistry.NiZn, 1.7m },
{ CellChemistry.NiMH, 1.2m }
};
为了保持一致性我会建议使用,而不是2 2M,但你并不需要到。
(你需要要么使CellChemistry
公众或使该领域的非公开ChemistryInfo
,或者使ChemistryInfo
非公有制。但是这是可访问的一致性的问题。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句