Getting Enum value via reflection

前端 未结 15 2502
梦如初夏
梦如初夏 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:34

    Get enum int value via reflection using this method

    protected static object PropertyValue(object obj, string propertyName)
    {
      var property = obj.GetType().GetProperty(propertyName);
      if(property == null)
        throw new Exception($"{propertyName} not found on {obj.GetType().FullName}");
    
      if (property.PropertyType.IsEnum)
        return (int) property.GetValue(obj);
      return property.GetValue(obj);
    }
    
    0 讨论(0)
  • 2020-12-05 02:39

    Why do you need reflection?

    int value = (int)TestEnum.TestOne;
    
    0 讨论(0)
  • 2020-12-05 02:40

    Or, if you needed the actual enum object (of type TestEnum) :

    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"; */ 
    
    // the actual enum object (of type MyEnum, above code is of type System.Reflection.RuntimeFieldInfo)
    object enumValue = memberInfos[i].GetValue(0);
    alerta += enumValue.ToString() + "\n";
    }
    
    0 讨论(0)
提交回复
热议问题