![](/img/trans.png)
[英]C# A method that will accept any List<enum> and return a string array
[英]C#: Create a generic method that can return an enum as List<string>
如何創建接收枚舉類型並將其值和名稱作為字符串列表返回的通用方法,以便我可以循環此列表,並且對於每次迭代,我將能夠打印每個枚舉值。 例如,考慮下一個偽:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.