C# 将枚举转换为人类可读的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13599/
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
Convert enums to human readable values
提问by Jedi Master Spooky
Does anyone know how to transform a enum value to a human readable value?
有谁知道如何将枚举值转换为人类可读的值?
For example:
例如:
ThisIsValueA should be "This is Value A".
ThisIsValueA 应该是“这是值 A”。
采纳答案by Leon Bambrick
Converting this from a vb code snippet that a certain Ian Horwill left at a blog post long ago... i've since used this in production successfully.
从某个 Ian Horwill很久以前在博客文章中留下的 vb 代码片段转换过来......我已经成功地在生产中使用了它。
/// <summary>
/// Add spaces to separate the capitalized words in the string,
/// i.e. insert a space before each uppercase letter that is
/// either preceded by a lowercase letter or followed by a
/// lowercase letter (but not for the first char in string).
/// This keeps groups of uppercase letters - e.g. acronyms - together.
/// </summary>
/// <param name="pascalCaseString">A string in PascalCase</param>
/// <returns></returns>
public static string Wordify(string pascalCaseString)
{
Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");
return r.Replace(pascalCaseString, " ${x}");
}
(requires, 'using System.Text.RegularExpressions;')
(需要,'使用 System.Text.RegularExpressions;')
Thus:
因此:
Console.WriteLine(Wordify(ThisIsValueA.ToString()));
Would return,
会回来,
"This Is Value A".
It's much simpler, and less redundant than providing Description attributes.
它比提供 Description 属性要简单得多,而且冗余更少。
Attributes are useful here only if you need to provide a layer of indirection (which the question didn't ask for).
仅当您需要提供一个间接层(问题没有要求)时,属性才有用。
回答by Matt Hamilton
Most examples of this that I've seen involve marking your enum values up with [Description] attributes and using reflection to do the "conversion" between the value and the description. Here's an old blog post about it:
我见过的大多数示例都涉及使用 [Description] 属性标记您的枚举值,并使用反射在值和描述之间进行“转换”。这是一篇关于它的旧博客文章:
http://geekswithblogs.net/rakker/archive/2006/05/19/78952.aspx
http://geekswithblogs.net/rakker/archive/2006/05/19/78952.aspx
回答by Scott Dorman
You can also take a look at this article: http://www.codeproject.com/KB/cs/enumdatabinding.aspx
你也可以看看这篇文章:http: //www.codeproject.com/KB/cs/enumdatabinding.aspx
It's specifically about data binding, but shows how to use an attribute to decorate the enum values and provides a "GetDescription" method to retrieve the text of the attribute. The problem with using the built-in description attribute is that there are other uses/users of that attribute so there is a possibility that the description appears where you don't want it to. The custom attribute solves that issue.
它专门针对数据绑定,但展示了如何使用属性来修饰枚举值并提供“GetDescription”方法来检索属性的文本。使用内置描述属性的问题在于该属性还有其他用途/用户,因此描述可能会出现在您不希望出现的地方。自定义属性解决了这个问题。
回答by Adam Haile
You can inherit from the "Attribute" class of System.Reflection to create your own "Description" class. Like this (from here):
您可以从 System.Reflection 的“Attribute”类继承以创建您自己的“Description”类。像这样(从这里):
using System;
using System.Reflection;
namespace FunWithEnum
{
enum Coolness : byte
{
[Description("Not so cool")]
NotSoCool = 5,
Cool, // since description same as ToString no attr are used
[Description("Very cool")]
VeryCool = NotSoCool + 7,
[Description("Super cool")]
SuperCool
}
class Description : Attribute
{
public string Text;
public Description(string text)
{
Text = text;
}
}
class Program
{
static string GetDescription(Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(Description), false);
if (attrs != null && attrs.Length > 0)
return ((Description)attrs[0]).Text;
}
return en.ToString();
}
static void Main(string[] args)
{
Coolness coolType1 = Coolness.Cool;
Coolness coolType2 = Coolness.NotSoCool;
Console.WriteLine(GetDescription(coolType1));
Console.WriteLine(GetDescription(coolType2));
}
}
}
回答by John
I found it best to define your enum values with an under score so ThisIsValueA would be This_Is_Value_A then you can just do a enumValue.toString().Replace("_"," ") where enumValue is your varible.
我发现最好用低分定义你的枚举值,所以 ThisIsValueA 将是 This_Is_Value_A 然后你可以做一个 enumValue.toString().Replace("_"," ") 其中 enumValue 是你的变量。
回答by Keith
The .ToString on Enums is relatively slow in C#, comparable with GetType().Name (it might even use that under the covers).
Enums 上的 .ToString 在 C# 中相对较慢,与 GetType().Name 相当(它甚至可能在幕后使用它)。
If your solution needs to be very quick or highly efficient you may be best of caching your conversions in a static dictionary, and looking them up from there.
如果您的解决方案需要非常快速或高效,您最好将转换缓存在静态字典中,然后从那里查找。
A small adaptation of @Leon's code to take advantage of C#3. This does make sense as an extension of enums - you could limit this to the specific type if you didn't want to clutter up all of them.
对@Leon 代码的小改动以利用 C#3。这作为枚举的扩展确实有意义 - 如果您不想将所有类型都弄乱,您可以将其限制为特定类型。
public static string Wordify(this Enum input)
{
Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");
return r.Replace( input.ToString() , " ${x}");
}
//then your calling syntax is down to:
MyEnum.ThisIsA.Wordify();
回答by Matt Williams
An alternative to adding Description
attributes to each enumeration is to create an extension method. To re-use Adam's "Coolness" enum:
Description
向每个枚举添加属性的另一种方法是创建扩展方法。重用 Adam 的“Coolness”枚举:
public enum Coolness
{
NotSoCool,
Cool,
VeryCool,
SuperCool
}
public static class CoolnessExtensions
{
public static string ToString(this Coolness coolness)
{
switch (coolness)
{
case Coolness.NotSoCool:
return "Not so cool";
case Coolness.Cool:
return "Cool";
case Coolness.VeryCool:
return "Very cool";
case Coolness.SuperCool:
return Properties.Settings.Default["SuperCoolDescription"].ToString();
default:
throw new ArgumentException("Unknown amount of coolness", nameof(coolness));
}
}
}
Although this means that the descriptions are further away from the actual values, it allows you to use localisation to print different strings for each language, such as in my VeryCool
example.
虽然这意味着描述离实际值更远,但它允许您使用本地化为每种语言打印不同的字符串,例如在我的VeryCool
示例中。