简体   繁体   English

C#更改枚举中的项目的int值

[英]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: 我想将watch的值(现在是4)更改为6。所以像这样:

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 : 根据Microsoft的C#文档

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list. enum关键字用于声明枚举,这是一种独特的类型,由一组称为枚举器列表的命名常量组成。

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. 但是当您需要整数值时,必须使用AssociatedValue[enumVal]代替(int)enumVal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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