如何在值共享相同名称的枚举之间进行转换?
如果我想在两个 Enum
类型之间进行转换,我希望其值具有相同的名称,是否有一种简洁的方法,或者我必须这样做:
enum colours_a { red, blue, green }
enum colours_b { yellow, red, blue, green }
static void Main(string[] args)
{
colours_a a = colours_a.red;
colours_b b;
//b = a;
b = (colours_b)Enum.Parse(typeof(colours_b), a.ToString());
}
?
If I want to convert between two Enum
types, the values of which, I hope, have the same names, is there a neat way, or do I have to do it like this:
enum colours_a { red, blue, green }
enum colours_b { yellow, red, blue, green }
static void Main(string[] args)
{
colours_a a = colours_a.red;
colours_b b;
//b = a;
b = (colours_b)Enum.Parse(typeof(colours_b), a.ToString());
}
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您对两个枚举有严格的控制,那么您的解决方案(或 兰多夫的)很好。
如果你不这样做,那么我会跳过尝试变得棘手并创建一个在它们之间进行转换的静态映射类。事实上,从易于维护的角度来看,我可能会建议这样做(即使您现在按名称进行映射)。
If you have strict control over the two enum's, then your solution (or Randolpho's) is fine.
If you don't, then I'd skip trying to be tricky and create a static mapping class that converts between them. In fact, I'd probably recommend that anyway (even if you map by name there for now), from an ease-of-maintenance perspective.
你也可以这样做,不知道它是否足够整洁:
这当然需要一个扩展方法:
You can also do this, don't know if it's neat enough:
This of course requires an extension method:
使用这个(根据需要将变量封装到新类中):
Use this (encapsulate variables to new class as needed):
您可以使用扩展:
you can use Extensions: