简体   繁体   中英

C# Change int value of item in enum

I have this enum

 enum Items { pen = 5, watch = 4, rubber = 1, ruler = 8};

and I want to change the value of watch (now is 4) to 6. So something like this:

Items.watch = 6;

but this doesn't work. Any ideas?

The value of an enum is fixed at compile time. According to Microsoft's C# documentation :

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

Note the term "constants". If you want to change the integer value of an enum entry, you must recompile the code.

There is no way to change numeric values of enum constants, because they are, well, constant.

You can associate a separate value with an enum by setting up a dictionary, but that would not change the values of the enum constants themselves:

private static IDictionary<Items,int> AssociatedValue = new Dictionary<Items,int> {
    {Items.pen, 5}, {Items.watch, 4}, {Items.rubber, 1}, {Items.ruler, 8}
};

Now you can set

AssociatedValue[Items.watch] = 6

but you would have to use AssociatedValue[enumVal] in place of (int)enumVal when you need the integer value.

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