枚举转换为另一种类型的枚举 [英] convert an enum to another type of enum
问题描述
我有例如枚举性别
(男= 0,女= 1
)和我具有有它自己的性别枚举服务另一个枚举(男= 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?
推荐答案
使用延长方法效果相当整齐,使用由内特提出的两种转换方式时:
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屋!