我怎样才能创建一个generic接收枚举类型并将其值和名称作为字符串列表返回的方法,因此我可以循环此列表,并且对于每次迭代,我将能够打印每个枚举值。例如,考虑下一个伪:
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;
}
再次注意,此方法可以获取任何类型的枚举
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();
}
现在如果你去
GetValues(typeof(MyEnum)).ForEach(Console.WriteLine);
将打印:
Value 5 Name A
Value 6 Name B
Value 8 Name C
非 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)