将枚举转换为另一种类型的枚举 [英] convert an enum to another type of enum

查看:26
本文介绍了将枚举转换为另一种类型的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举,例如Gender"(Male =0,Female =1),我有另一个来自具有自己的 Gender 枚举的服务的枚举(男 =0, 女 =1, 未知 =2)

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 , Female =1, Unknown =2)

我的问题是我怎样才能写出快速而漂亮的东西来从他们的枚举转换为我的枚举?

My question is how can I write something quick and nice to convert from their enum to mine?

推荐答案

当使用 Nate 建议的两种转换方法时,使用扩展方法非常有效:

Using an extension method works quite neatly, when using the two conversion methods suggested by Nate:

public static class TheirGenderExtensions
{
    public static MyGender ToMyGender(this TheirGender value)
    {
        // insert switch statement here
    }
}

public static class MyGenderExtensions
{
    public static TheirGender ToTheirGender(this MyGender value)
    {
        // insert switch statement here
    }
}

显然,如果您不想,则无需使用单独的类.我的偏好是将扩展方法按它们适用的类/结构/枚举分组.

Obviously there's no need to use separate classes if you don't want to. My preference is to keep extension methods grouped by the classes/structures/enumerations they apply to.

这篇关于将枚举转换为另一种类型的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆