动态改变C#中枚举的值?
我有一个
public enum TestType:int
{
Aphasia = 2,
FocusedAphasia = 5
}
设置了值的枚举。我想将枚举“FocusedAphasia”的值从 5 更改为 10。任何人都可以帮助我在运行时更改枚举的值
I have a enum
public enum TestType:int
{
Aphasia = 2,
FocusedAphasia = 5
}
with values set. I want to change the value of the enum 'FocusedAphasia' from 5 to 10. Can anyone help me in changing the value of enum at runtime
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法在运行时更改枚举。我不知道为什么你需要这样做,但无论如何这是不可能的。使用变量是另一种选择。
You cannot change enums at runtime. I'm not sure why you'd ever need to, but in any case it's not possible. Using a variable would be the alternative.
你不能这样做,如果你愿意的话,它是一个强类型值。
枚举的元素是只读的,并且在运行时更改它们是不可能的,也不是可取的。
可能适合您的是枚举的扩展,以公开与新功能等一起使用的新值,例如:
不太清楚您想要做什么,我不能很好还有很多其他建议。
You can't do this, it is a strongly-typed value, if you like.
The elements of the enum are read-only and changing them at runtime is not possible, nor would it be desirable.
What might suit you is extension of the enum to expose a new value to use with new features and whatnot, such as:
Not being quite clued up on exactly what you want to do, I can't well suggest much else.
好吧,这个问题距我写答案已经七年了。我还是想写一下,也许对以后的人有用。
在运行时更改枚举值是不可能的,但是有一种方法可以通过将 int 变量转换为枚举,并在字典中定义这些整数及其值,如下所示:
这样,您就拥有了枚举值的动态字典里面没有任何文字。
如果您想要枚举的任何其他值,那么您可以创建一个方法来添加它:
因此,您最后使用的代码应该是这样的:
Well, this question is 7 years far while I am writing my answer. I still want to write it, maybe it will be useful for someone later.
Changing enum values in runtime is not possible, but there is a way to play around by casting int variable into enum, and defining those ints with their values in a dictionary as in below:
In this way, you have a dynamic dictionary for enum values without any written inside it.
In case you want any other value for the enum, then you can make a method to add it:
So, your last code in use should be this way:
其实你可以。假设您有一个带有原始 TestType 的程序集 (dll)。您可以卸载该程序集(这有点复杂),使用新的 TestType 重写该程序集并重新加载它。
但是,您无法更改现有变量的类型,因为必须在卸载程序集之前处理掉这些变量。
Well actually you can. Say you have an assembly (dll) with the original TestType. You can unload that assembly (this is somewhat complicated), rewrite the assembly with a new TestType and reload it.
You can not, however, change the type of existing variables because those have to be disposed of before the assembly can be unloaded.