所有枚举项到字符串 (C#)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/737917/
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
All Enum items to string (C#)
提问by Maciej
How to convert all elements from enum to string?
如何将所有元素从枚举转换为字符串?
Assume I have:
假设我有:
public enum LogicOperands {
None,
Or,
And,
Custom
}
And what I want to archive is something like:
我想要存档的是这样的:
string LogicOperandsStr = LogicOperands.ToString();
// expected result: "None,Or,And,Custom"
采纳答案by Moose
string s = string.Join(",",Enum.GetNames(typeof(LogicOperands)));
回答by CookieOfFortune
foreach (string value in Enum.GetNames(typeof(LogicOoperands))
{
str = str + "," + value;
}
回答by Keltex
You have to do something like this:
你必须做这样的事情:
var sbItems = new StringBuilder()
foreach (var item in Enum.GetNames(typeof(LogicOperands)))
{
if(sbItems.Length>0)
sbItems.Append(',');
sbItems.Append(item);
}
Or in Linq:
或者在 Linq 中:
var list = Enum.GetNames(typeof(LogicOperands)).Aggregate((x,y) => x + "," + y);
回答by Vivek
string LogicOperandsStr
= Enum.GetNames(typeof(LogicOoperands)).Aggregate((current, next)=>
current + "," + next);
回答by Randolpho
Although @Moose's answer is the best, I suggest you cache the value, since you might be using it frequently, but it's 100% unlikely to change during execution -- unless you're modifying and re-compiling the enum. :)
尽管@Moose 的答案是最好的,但我建议您缓存该值,因为您可能经常使用它,但在执行过程中它 100% 不太可能更改——除非您正在修改和重新编译枚举。:)
Like so:
像这样:
public static class LogicOperandsHelper
{
public static readonly string OperandList =
string.Join(",", Enum.GetNames(typeof(LogicOperands)));
}
回答by Gabriel
A simple and generic way to convert a enum to something you can interact:
将枚举转换为可以交互的内容的简单而通用的方法:
public static Dictionary<int, string> ToList<T>() where T : struct
{
return ((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(item => Convert.ToInt32(item), item => item.ToString());
}
and then:
进而:
var enums = EnumHelper.ToList<MyEnum>();