在C#中以枚举为键创建静态只读字典

杰森·奥(Jason O)

我正在尝试使用程序的一些硬编码参考信息创建一个静态类。该静态类包含一个枚举和一个参考字典,该字典使用该枚举选择一组预定义的数值。这是我在下面做什么的示例:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章