convert an enum to another type of enum

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

    You could write a simple generic extension method like this

    public static T ConvertTo(this object value)            
        where T : struct,IConvertible
    {
        var sourceType = value.GetType();
        if (!sourceType.IsEnum)
            throw new ArgumentException("Source type is not enum");
        if (!typeof(T).IsEnum)
            throw new ArgumentException("Destination type is not enum");
        return (T)Enum.Parse(typeof(T), value.ToString());
    }
    

提交回复
热议问题