.net 将枚举转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/483794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 11:06:05  来源:igfitidea点击:

Convert Enum to String

.netenums

提问by Eric Weilnau

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

在 .NET 3.5 中将 Enum 转换为 String 的首选方法是什么?

  • Enum.GetName
  • Enum.Format
  • ToString
  • 枚举.GetName
  • 枚举格式
  • 字符串

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

为什么我应该更喜欢其中之一而不是其他?一个表现更好吗?

采纳答案by Keith

As of C#6 the best way to get the name of an enum is the new nameofoperator:

从 C#6 开始,获取枚举名称的最佳方法是使用 newnameof运算符:

nameof(MyEnum.EnumValue);

// Ouputs
> "EnumValue"

This works at compile time, with the enum being replaced by the string in the compiled result, which in turn means this is the fastest way possible.

这在编译时起作用,枚举被编译结果中的字符串替换,这反过来意味着这是最快的方法。

Any use of enum names does interfere with code obfuscation, if you consider obfuscation of enum names to be worthwhile or important - that's probably a whole other question.

枚举名称的任何使用都会干扰代码混淆,如果您认为枚举名称的混淆是值得或重要的 - 那可能是另一个问题。

回答by Sumtraveller

Works for our project...

适用于我们的项目...

public static String convertToString(this Enum eff)
{
    return Enum.GetName(eff.GetType(), eff);
}

public static EnumType converToEnum<EnumType>(this String enumValue)  
{
    return (EnumType) Enum.Parse(typeof(EnumType), enumValue);
}

回答by nawfal

In my tests, Enum.GetNamewas faster and by decent margin. Internally ToStringcalls Enum.GetName. From sourcefor .NET 4.0, the essentials:

在我的测试中,Enum.GetName速度更快,幅度也不错。内部ToString调用Enum.GetName.NET 4.0 的源代码来看,要点:

public override String ToString()
{
     return Enum.InternalFormat((RuntimeType)GetType(), GetValue());
}

private static String InternalFormat(RuntimeType eT, Object value)
{
    if (!eT.IsDefined(typeof(System.FlagsAttribute), false))
    {
        String retval = GetName(eT, value); //<== the one
        if (retval == null)
            return value.ToString();
        else
            return retval;
    }
    else
    {
        return InternalFlagsFormat(eT, value);
    }
}

I cant say that is the reason for sure, but tests state one is faster than the other. Both the calls involve boxing (in fact they are reflection calls, you're essentially retrieving field names) and can be slow for your liking.

我不能说这是肯定的原因,但测试表明一个比另一个更快。这两个调用都涉及装箱(实际上它们是反射调用,您实际上是在检索字段名称)并且可能会根据您的喜好变慢。

Test setup: enum with 8 values, no. of iterations = 1000000

Result: Enum.GetName => 700 ms, ToString => 2000 ms

测试设置:具有 8 个值的枚举,没有。迭代次数 = 1000000

结果:Enum.GetName => 700 毫秒,ToString => 2000 毫秒

If speed isn't noticeable, I wouldn't care and use ToStringsince it offers a much cleaner call. Contrast

如果速度不明显,我不会关心和使用,ToString因为它提供了一个更清晰的调用。对比

Enum.GetName(typeof(Bla), value)

with

value.ToString()

回答by Andrei

Enum.GetName(...)

Enum.GetName(...)

This is the most elegant method that is meant for it.

这是最优雅的方法。

var enumValueString = Enum.GetName(typeof (MyEnum), MyEnum.MyValue);

Although I don't see any issues with calling .ToString()as it is simply shorter.

尽管我认为通话没有任何问题,.ToString()因为它只是更短。

var enumValueString = MyEnum.MyValue.ToString();


With new C# 6 syntax you can use:

使用新的 C# 6 语法,您可以使用:

nameof(MyEnum.MyValue)

回答by David Morton

All of these internally end up calling a method called InternalGetValueAsString. The difference between ToStringand GetNamewould be that GetNamehas to verify a few things first:

所有这些在内部最终都会调用一个名为InternalGetValueAsString. ToStringGetName将之间的区别在于GetName必须首先验证一些事情:

  1. The type you entered isn't null.
  2. The type you entered is, in fact an enumeration.
  3. The value you passed in isn't null.
  4. The value you passed in is of a type that an enumeration can actually use as it's underlying type, or of the type of the enumeration itself. It uses GetTypeon the value to check this.
  1. 您输入的类型不为空。
  2. 您输入的类型实际上是一个枚举。
  3. 您传入的值不为空。
  4. 您传入的值属于枚举实际可以用作其基础类型的类型,或者属于枚举本身的类型。它使用GetType值来检查这一点。

.ToStringdoesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToStringmethod doesn't have the same verification issues as the static methods, I would conclude that .ToStringis the fastest way to get the value as a string.

.ToString不必担心上述任何问题,因为它是在类本身的实例上调用的,而不是在传入的版本上调用,因此,由于该.ToString方法没有相同的验证问题作为静态方法,我认为这.ToString是以字符串形式获取值的最快方法。

回答by David Morton

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.

我能找到的最好的是MSDN 上的这个不相关的问题,其中包含回答这个问题的 XML 片段。这些方法中的任何一个都有相同的缺陷:它们调用enum.toString(),在使用Dotfuscation时无法正常工作。其他问题似乎与间接拳击(GetName 和 Format)有关。不幸的是,我找不到使用上述任何一个的任何性能原因。

Paraphrasing from the xml snippet,

xml 片段转述

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.

将装箱枚举传递给 string.Format() 或任何其他函数可能会导致enum.ToString()被调用。这会在 Dotfuscating 时导致问题。您不应使用enum.ToString(), enum.GetNames(), enum.GetName(),enum.Format()enum.Parse()将枚举转换为字符串。相反,使用 switch 语句,并在必要时将名称国际化。

回答by Tamas Czinege

Enum.GetName()

Enum.GetName()

Format()is really just a wrapper around GetName()with some formatting functionality (or InternalGetValueAsString()to be exact). ToString()is pretty much the same as Format(). I think GetName()is best option since it's totally obvious what it does for anyone who reads the source.

Format()实际上只是一个GetName()带有一些格式化功能的包装器(或者InternalGetValueAsString()确切地说)。ToString()与 几乎相同Format()。我认为这GetName()是最好的选择,因为对于阅读源代码的任何人来说,它的作用是完全显而易见的。

回答by DancesWithBamboo

I create a "Description" extension method and attach it to the enum so that i can get truly user-friendly naming that includes spaces and casing. I have never liked using the enum value itself as displayable text because it is something we developers use to create more readable code. It is not intended for UI display purposes. I want to be able to change the UI without going through and changing enums all over.

我创建了一个“描述”扩展方法并将其附加到枚举,以便我可以获得真正用户友好的命名,包括空格和大小写。我从不喜欢使用枚举值本身作为可显示文本,因为我们开发人员使用它来创建更具可读性的代码。它不适用于 UI 显示目的。我希望能够在不经历和更改枚举的情况下更改 UI。

回答by Perry Neal

I don't know what the "preferred" method is (ask 100 people and get 100 different opinions) but do what's simplest and what works. GetNameworks but requires a lot more keystrokes. ToString()seems to do the job very well.

我不知道什么是“首选”方法(询问 100 个人并得到 100 种不同的意见),但做最简单和有效的方法。 GetName工作,但需要更多的击键。 ToString()似乎做得很好。

回答by GlennG

For VB aficionados:

对于VB爱好者:

EnumStringValue = System.Enum.GetName(GetType(MyEnum), MyEnumValue)