[英]Creating Static readonly dictionary with enum as key in C#
I am trying to create a static class with some hard-coded reference information for a program. 我正在尝试创建一个静态类,其中包含一些程序的硬编码参考信息。 This static class contains an enum and a reference dictionary, which uses the enum to select a set of pre-defined numeric values. 此静态类包含枚举和引用字典,它使用枚举来选择一组预定义的数值。 Here's an example of what I am doing below: 这是我在下面做的一个例子:
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 }
};
}
But I keep getting a syntax error on the line that says, { CellChemistry.PbAc, 2 },
to initialize the Dictionary saying, 但是我继续在{ CellChemistry.PbAc, 2 },
这一行上得到一个语法错误来初始化词典,
The Best overloaded Add method 'Dictionary<CellChemistry, decimal>.Add(CellChemistry, decimal)' for the collection initializer has some invalid arguments.
What does this mean and how can I fix it? 这是什么意思,我该如何解决?
The problem is that there's no implicit conversion from double
to decimal
. 问题是没有从double
到decimal
隐式转换。 You can see this if you try to just assign the values to variables: 如果您尝试将值分配给变量,则可以看到此信息:
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
You want to use decimal literals instead - using an m
suffix: 您想使用十进制文字 - 使用m
后缀:
public static readonly Dictionary<CellChemistry, decimal> NominalVoltage = new Dictionary<CellChemistry, decimal>
{
{ CellChemistry.PbAc, 2 },
{ CellChemistry.NiZn, 1.7m },
{ CellChemistry.NiMH, 1.2m }
};
For consistency I'd suggest using 2m instead of 2, but you don't need to. 为了保持一致性,我建议使用2m而不是2,但你不需要 。
(You do need to either make CellChemistry
public or make the field non-public in ChemistryInfo
. Or make ChemistryInfo
non-public. But that's a matter of accessibility consistency.) (您确实需要公开CellChemistry
或在ChemistryInfo
将该字段CellChemistry
非公开。或者使ChemistryInfo
非公开。但这是可访问性一致性的问题。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.