convert an enum to another type of enum

前端 未结 15 1550
感动是毒
感动是毒 2020-11-30 02:36

I have an enum of for example \'Gender\' (Male =0 , Female =1) and I have another enum from a service which has its own Gender enum (Male =0

相关标签:
15条回答
  • 2020-11-30 03:29

    Here's an extension method version if anyone is interested

    public static TEnum ConvertEnum<TEnum >(this Enum source)
        {
            return (TEnum)Enum.Parse(typeof(TEnum), source.ToString(), true);
        }
    
    // Usage
    NewEnumType newEnum = oldEnumVar.ConvertEnum<NewEnumType>();
    
    0 讨论(0)
  • 2020-11-30 03:33

    Given Enum1 value = ..., then if you mean by name:

    Enum2 value2 = (Enum2) Enum.Parse(typeof(Enum2), value.ToString());
    

    If you mean by numeric value, you can usually just cast:

    Enum2 value2 = (Enum2)value;
    

    (with the cast, you might want to use Enum.IsDefined to check for valid values, though)

    0 讨论(0)
  • Just cast one to int and then cast it to the other enum (considering that you want the mapping done based on value):

    Gender2 gender2 = (Gender2)((int)gender1);
    
    0 讨论(0)
提交回复
热议问题