Getting Enum value via reflection

前端 未结 15 2500
梦如初夏
梦如初夏 2020-12-05 01:35

I have a simple Enum

 public enum TestEnum
 {
     TestOne = 3,
     TestTwo = 4
 }

var testing = TestEnum.TestOne;

And I want to retrieve

相关标签:
15条回答
  • 2020-12-05 02:18

    Full code : How to Get Enum Values with Reflection in C#

    MemberInfo[] memberInfos = typeof(MyEnum).GetMembers(BindingFlags.Public | BindingFlags.Static);
    string alerta = "";
    for (int i = 0; i < memberInfos.Length; i++) {
    alerta += memberInfos[i].Name + " - ";
    alerta += memberInfos[i].GetType().Name + "\n";
    }
    
    0 讨论(0)
  • 2020-12-05 02:19

    For your requirement it's as simple as people already pointed it out. Just cast the enum object to int and you'd get the numeric value of the enum.

    int value = (int) TestEnum.TestOne;
    

    However, if there is a need to mix-down enum values with | (bitwise OR) e.g.

    var value = TestEnum.TestOne | TestEnum.TestTwo;
    

    and you wish to get what options that mixed-down value represents, here is how you could do it (note: this is for enums that represented by int values intended to take advantage of bitwise operatations) :

    first, get the enum options along with their values in a dictionary.

    var all_options_dic = typeof(TestEnum).GetEnumValues().Cast<object>().ToDictionary(k=>k.ToString(), v=>(int) v);
    

    Filter the dictionary to return only the mixed-down options.

    var filtered = all_options_dic.Where(x => (x.Value & (int) options) != 0).ToDictionary(k=>k.Key, v=>v.Value);
    

    do whatever logic with your options. e.g. printing them, turning them to List, etc..:

    foreach (var key in filtered.Keys)
            {
                Console.WriteLine(key + " = " + filtered[key]);
            }
    

    hope this helps.

    0 讨论(0)
  • 2020-12-05 02:22

    There must be a motivation to ask a question like this. Here I have one real life scenario with good motivation to do something like this and the solution to this problem.

    Motivation

    2 assemblies with circular references. One reference is hard reference, i.e. <Reference . . .> tag in project file. And a soft reference in opposite direction. assembly1 must call some object, some method in assembly2. Method's argument is enum

    Here is the code that will get enum value. The assembly is already loaded at the time of calling this method because instance of the object containing method already loaded

    Solution

    internal static object GetEnumValue(string assemblyName, string enumName, string valueName) // we know all these 
    {
        var assembly = Assembly.Load(assemblyName);
        var converter = new EnumConverter(assembly.GetType(enumName)); 
        object enumVal = converter.ConvertFromString(valueName);
        return enumVal;
    }
    

    And the usage

    dynamic myInstance = GetInstanceOfKnownObject(.......); // this preloads assembly for first time. All sequential loads are easy
    dynamic enumArg = GetEnumValue("assemblyName", "assembly2.namespace1.EnumName", "enumValueName"); // important to load into 'dynamic', not 'object'
    myInstance.MyMethod(enumArg);
    

    Bottom line - it is really useful when one assembly has no idea (and can't have knowledge) of the other assembly internals.

    0 讨论(0)
  • 2020-12-05 02:23

    No need for reflection:

    int value = (int)TestEnum.TestOne;
    
    0 讨论(0)
  • 2020-12-05 02:25
    System.Type.GetType("Namespace Name" + "." + "Class Name" + "+" + "Enum Name")
    
    Dim fieldInfos() As System.Reflection.FieldInfo = System.Type.GetType("YourNameSpaceName.TestClass+TestEnum").GetFields
    
    For Each f As System.Reflection.FieldInfo In fieldInfos 
        If f.IsLiteral Then 
            MsgBox(f.Name & " : " & CType(f.GetValue(Nothing), Integer) & vbCrLf) 
        End If 
    Next 
    
    Public Class TestClass
        Public Enum TestEnum
            val1 = 20
            val2 = 30
        End Enum
    End Class
    

    That works

    0 讨论(0)
  • 2020-12-05 02:27

    Hi you have this alternative:

    Type typevar = GetType([YourEnum])

    And then ... ... You can get names using typevar.GetEnumNames returning a array with names and to get values using type.GetEnumValues, returning an array with values.

    0 讨论(0)
提交回复
热议问题