简体   繁体   中英

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,

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 . 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:

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.

(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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM