convert an enum to another type of enum

前端 未结 15 1608
感动是毒
感动是毒 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:28

    public static TEnum ConvertByName(this Enum source, bool ignoreCase = false) where TEnum : struct
    {
        // if limited by lack of generic enum constraint
        if (!typeof(TEnum).IsEnum)
        {
            throw new InvalidOperationException("enumeration type required.");
        }
    
        TEnum result;
        if (!Enum.TryParse(source.ToString(), ignoreCase, out result))
        {
            throw new Exception("conversion failure.");
        }
    
        return result;
    }
    

提交回复
热议问题