[英]C#: Create a generic method that can return an enum as List<string>
How can I create a generic method that receives an enum type and return its values and names as a list of strings, so I could loop this list and for each iteration I'll be able to print each of the enum values.如何创建接收枚举类型并将其值和名称作为字符串列表返回的通用方法,以便我可以循环此列表,并且对于每次迭代,我将能够打印每个枚举值。 For example, consider the next pseudo:
例如,考虑下一个伪:
enum MyEnum { A=5, B=6, C=8 }
List<string> createEnumStrings(AnyEnum(??))
{
List<string> listResult;
// ??
// a code that will generate:
// listResult[0] = "Value 5 Name A"
// listResult[1] = "Value 6 Name B"
// lsitResult[2] = "Value 8 Name C"
return listResult;
}
Again, note that this method can get any type of an enum再次注意,此方法可以获取任何类型的枚举
public List<string> GetValues(Type enumType)
{
if(!typeof(Enum).IsAssignableFrom(enumType))
throw new ArgumentException("enumType should describe enum");
var names = Enum.GetNames(enumType).Cast<object>();
var values = Enum.GetValues(enumType).Cast<int>();
return names.Zip(values, (name, value) => string.Format("Value {0} Name {1}", value, name))
.ToList();
}
now if you go with现在如果你去
GetValues(typeof(MyEnum)).ForEach(Console.WriteLine);
will print:将打印:
Value 5 Name A
Value 6 Name B
Value 8 Name C
Non-LINQ version:非 LINQ 版本:
public List<string> GetValues(Type enumType)
{
if(!typeof(Enum).IsAssignableFrom(enumType))
throw new ArgumentException("enumType should describe enum");
Array names = Enum.GetNames(enumType);
Array values = Enum.GetValues(enumType);
List<string> result = new List<string>(capacity:names.Length);
for (int i = 0; i < names.Length; i++)
{
result.Add(string.Format("Value {0} Name {1}",
(int)values.GetValue(i), names.GetValue(i)));
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.