我正在尝试为程序创建一个带有一些硬编码引用信息的静态类。这个静态类包含一个枚举和一个引用字典,它使用枚举来选择一组预定义的数值。下面是我正在做的一个例子:
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 },
的行中收到语法错误初始化字典 saying,
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 }
};
为了保持一致性,我建议使用 2m 而不是 2,但您不需要。
(您需要在 ChemistryInfo
中将 CellChemistry
公开或将字段设为非公开。或者将 ChemistryInfo
设为非公开。但这是可访问性一致性的问题。)
关于c# - 在 C# 中创建以枚举为键的静态只读字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52062890/