代码之家  ›  专栏  ›  技术社区  ›  Raphael Ribeiro

如何获取具有枚举类型名称和枚举选项名称的枚举值

  •  -3
  • Raphael Ribeiro  · 技术社区  · 8 年前

    public enum SomeEnum
    {
       None,
       Half,
       All
    }
    

    下面的方法体如何,因此我可以获得值1,并将选项“None”和枚举名“SomeEnum”存储为字符串:

    string enumTypeName = "SomeEnum";
    string enumPickedOptionName = "None";
    

    public int GetEnumValue(string enumTypeName, string enumPickedOptionName){}
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   user8217724 user8217724    8 年前

    在枚举名称之前使用“名称空间”进行尝试:

    private int GetEnumValue(string enumTypeName, string enumPickedOptionName)
        {
            int result = -1;
            Type enumType;
    
            try
            {
                enumType= Type.GetType(enumTypeName);
                result = (int)Enum.Parse(enumType, enumPickedOptionName,true);
            }
            catch (Exception ex)
            {
    
            }
            finally
            {
    
            }
    
            return result;
        }
    

        2
  •  0
  •   Raphael Ribeiro    8 年前

    我这样解决了这个问题:

    private int GetEnumValue(string assemblyName, string enumTypeName, string enumPickedOptionName)
    {
        int result = -1;
    
        Assembly assembly = Assembly.Load(assemblyName);
        Type enumType = assembly.GetTypes().Where(x => x.Name == 
        enumTypeName).FirstOrDefault();
    
        result = (int)Enum.Parse(enumType, enumPickedOptionName, true);
    
        return result;
    }