枚举转换为字符串 [英] Convert Enum to String

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

问题描述

这是preferred的方式来枚举转换为字符串在.NET 3.5?

  • Enum.GetName
  • Enum.Format
  • 的toString

我为什么要preFER其中一个比其他人呢?做一件有更好的表现?

理由为接受的答案

根据在panesofglass回答论坛上的帖子,看来微软间接认可枚举值转换为字符串的下面的方法。

  

枚举值,使用不转换为字符串内置的枚举的方法。

     

...

     

Dotfuscating时,这会引起问题。你不应该使用enum.ToString(),enum.GetNames(),enum.GetName(),enum.Format()或enum.Parse(),以枚举转换为字符串。相反,使用switch语句,并且如果有必要国际化的名字。

解决方案

尽我所能找到的是<一个href="http://social.msdn.microsoft.com/Forums/en-US/vsts$c$c/thread/78f9dfe5-2d81-4f5d-b5a9-d0be5349276d/">this在MSDN ,它要求一个不同的问题,但规则的XML描述问题的原因为打破 Dotfuscation 。任何其他问题似乎涉及到间接拳击(的GetName和格式)。不幸的是,我找不到任何性能原因使用上述任何一种。

Which is the preferred way to convert an Enum to a String in .NET 3.5?

  • Enum.GetName
  • Enum.Format
  • toString

Why should I prefer one of these over the others? Does one perform better?

Justification for Accepted Answer

Based on the forum post in panesofglass answer, it appears that Microsoft indirectly endorses the following method of converting an enum value to a string.

Do not convert an enum value to a string using built-in enum methods.

...

This will cause problems when Dotfuscating. You should not use enum.ToString(), enum.GetNames(), enum.GetName(), enum.Format() or enum.Parse() to convert an enum to a string. Instead, use a switch statement, and also internationalize the names if necessary.

解决方案

Best I can find is this question on MSDN, which asks a different question, but the rule XML describe the reason as breaking Dotfuscation. Any other concerns appear to relate to indirect boxing (GetName and Format). Unfortunately, I can't find any performance reasons for using any of the above.

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

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