Setting enum value at runtime in C#

我的未来我决定 提交于 2019-12-01 15:29:39

Just refer to MSDN help HERE

  • 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.

To answer your question - No it is not possible.

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.

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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!