简体   繁体   English

在C#中设置运行时的枚举值

[英]Setting enum value at runtime in C#

Is there any way that I can change enum values at run-time? 有什么办法可以在运行时更改enum值吗?

eg I have following type 例如,我有以下类型

enum MyType
{
   TypeOne, //=5 at runtime 
   TypeTwo  //=3 at runtime
}

I want at runtime set 5 to TypeOne and 3 to TypeTwo . 我想在运行时将set 5设置为TypeOne ,将3设置为TypeTwo

As others have pointed out, the answer is no. 正如其他人所指出的那样,答案是否定的。

You could however probably refactor your code to use a class instead: 但是,您可以重构代码以使用类:

public sealed class MyType
{
   public int TypeOne { get; set; }
   public int TypeTwo { get; set; }
}

...

var myType = new MyType { TypeOne  = 5, TypeTwo = 3 };

or variations on that theme. 或该主题的变化。

Just refer to MSDN help HERE 这里只需参考MSDN帮助

  • An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. 枚举类型(也称为枚举或枚举)提供了一种有效的方法来定义可以分配给变量的一组命名的整数常量。

Also HERE 还在这里

In the Robust Programming Section - Just as with any constant, all references to the individual values of an enum are converted to numeric literals at compile time . 在强健编程部分 - 与任何常量一样,对枚举的各个值的所有引用在编译时都转换为数字文字。

So you need to realign your idea of Enum and use it accordingly. 因此,您需要重新调整Enum的想法并相应地使用它。

To answer your question - No it is not possible. 回答你的问题 - 不,这是不可能的。

Enums are compiled as constant static fields, their values are compiled into you assembly, so no, it's not possible to change them. 枚举被编译为常量静态字段,它们的值被编译到汇编中,所以不,它们不可能更改它们。 (Their constant values may even be compiled into places where you reference them.) (它们的常量值甚至可以编译到您引用它们的位置。)

Eg take this enum: 举这个枚举:

enum foo
{
    Value = 3
}

Then you can get the field and its information like this: 然后你可以得到这个字段及其信息:

var field = typeof(foo).GetField("Value", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
Console.WriteLine(field.GetValue(null));
Console.WriteLine(field.Attributes);

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

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