枚举转换为字符串转换为、字符串

2023-09-02 20:43:26 作者:ㄟ有鹿

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

Enum.GetName Enum.Format 的toString

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

理由为接受的答案

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

  

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

     

...

     

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

解决方案

尽我所能找到的是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 Qt中枚举类型转字符串输出 enum转QString

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.