动态更改C#中枚举的值?

我有一个枚举

public enum TestType:int { Aphasia = 2, FocusedAphasia = 5 } 

设置值。 我想将枚举’FocusedAphasia’的值从5更改为10.任何人都可以帮助我在运行时更改枚举的值

您无法在运行时更改枚举。 我不确定你为什么需要,但无论如何它是不可能的。 使用变量将是另一种选择。

如果你愿意,你不能这样做,它是一个强类型的值

枚举的元素是只读的,在运行时更改它们是不可能的,也不是理想的。

可能适合您的是扩展枚举以暴露新值以用于新function和诸如此类的东西,例如:

 public enum TestType:int { Aphasia = 2, FocusedAphasia = 5 SomeOtherAphasia = 10 } 

对于你想要做的事情并没有完全了解,我不能提出太多建议。

实际上你可以。 假设你有一个带有原始TestType的程序集(dll)。 您可以卸载该程序集(这有点复杂),使用新的TestType重写程序集并重新加载它。

但是,您无法更改现有变量的类型,因为在卸载程序集之前必须先处理这些变量。

那么,这个问题已经有7年了,而我正在写我的答案。 我仍然想写它,也许以后对某人有用。

在运行时更改枚举值是不可能的,但有一种方法可以通过将int变量转换为枚举来定义,并在字典中使用它们的值定义这些int,如下所示:

 // Define enum TestType without values enum TestType{} // Define a dictionary for enum values Dictionary d = new Dictionary(); void Main() { int i = 5; TestType s = (TestType)i; TestType e = (TestType)2; // Definging enum int values with string values d.Add(2,"Aphasia"); d.Add(5,"FocusedAphasia"); // Results: Console.WriteLine(d[(int)s]); // Result: FocusedAphasia Console.WriteLine(d[(int)e]); // Result: Aphasia } 

通过这种方式,您可以获得枚举值的动态字典,而无需在其中写入任何内容。 如果你想要枚举的任何其他值,那么你可以创建一个方法来添加它:

 public void NewEnumValue(int i, string v) { try { string test = d[i]; Console.WriteLine("This Key is already assigned with value: " + test); } catch { d.Add(i,v); } } 

因此,您使用的最后一个代码应该是这样的:

 // Define enum TestType without values enum TestType{} // Define a dictionary for enum values Dictionary d = new Dictionary(); public void NewEnumValue(int i, string v) { try { string test = d[i]; Console.WriteLine("This Key is already assigned with value: " + test); } catch { d.Add(i,v); Console.WriteLine("Addition Done!"); } } void Main() { int i = 5; TestType s = (TestType)i; TestType e = (TestType)2; // Definging enum int values with string values NewEnumValue(2,"Aphasia"); NewEnumValue(5,"FocusedAphasia"); Console.WriteLine("You will add int with their values; type 0 to " + "exit"); while(true) { Console.WriteLine("enum int:"); int ii = Convert.ToInt32(Console.ReadLine()); if (ii == 0) break; Console.WriteLine("enum value:"); string v = Console.ReadLine(); Console.WriteLine("will try to assign the enum TestType with " + "value: " + v + " by '" + ii + "' int value."); NewEnumValue(ii,v); } // Results: Console.WriteLine(d[(int)s]); // Result: FocusedAphasia Console.WriteLine(d[(int)e]); // Result: Aphasia }