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

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

问题描述




  • Enum.GetName

  • Enum.Format

  • toString



为什么我更喜欢这些超过其他?一个表现更好?

解决方案

最好我可以找到是这个与MSDN无关的问题,其中包含一个解答此问题的XML代码段。任何这些方法都有同样的缺陷:它们调用 enum.toString(),当使用 Dotfuscation 。其他问题似乎与间接拳击(GetName和格式)有关。不幸的是,我找不到任何使用上述任何性能的原因。



xml片段



<传递一个盒装枚举到string.Format()或任何其他函数可以导致$ code> enum.ToString()被调用。
这会导致Dotfuscating的问题。你不应该使用 enum.ToString() enum.GetNames()枚举。 GetName() enum.Format() enum.Parse()一个字符串的枚举而是使用switch语句,如果需要,也可以将名称进行国际化。



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?

解决方案

Best I can find is this unrelated question on MSDN, which contains an XML snippet that answers this question. Any of these methods share the same flaw: they call enum.toString(), which does not work properly when using Dotfuscation. 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.

Paraphrasing from the xml snippet,

Passing a boxed enum to string.Format() or any other function can result in enum.ToString() being called. 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.

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

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