在.Net中,可以通过使用迭代遍历枚举
System.Enum.GetNames(typeof(MyEnum))
Run Code Online (Sandbox Code Playgroud)
要么
System.Enum.GetValues(typeof(MyEnum))
Run Code Online (Sandbox Code Playgroud)
但是,在Silverlight 3中,未定义Enum.GetNames和Enum.GetValues.有没有人知道另一种选择?
pto*_*son 30
或者可能使用linq强类型,如下所示:
public static T[] GetEnumValues<T>()
{
var type = typeof(T);
if (!type.IsEnum)
throw new ArgumentException("Type '" + type.Name + "' is not an enum");
return (
from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
where field.IsLiteral
select (T)field.GetValue(null)
).ToArray();
}
public static string[] GetEnumStrings<T>()
{
var type = typeof(T);
if (!type.IsEnum)
throw new ArgumentException("Type '" + type.Name + "' is not an enum");
return (
from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
where field.IsLiteral
select field.Name
).ToArray();
}
Run Code Online (Sandbox Code Playgroud)
eri*_*200 27
我想出了如何在不对枚举进行假设的情况下做到这一点,模仿.Net中的函数:
public static string[] GetNames(this Enum e) {
List<string> enumNames = new List<string>();
foreach (FieldInfo fi in e.GetType().GetFields(BindingFlags.Static | BindingFlags.Public)){
enumNames.Add(fi.Name);
}
return enumNames.ToArray<string>();
}
public static Array GetValues(this Enum e) {
List<int> enumValues = new List<int>();
foreach (FieldInfo fi in e.GetType().GetFields(BindingFlags.Static | BindingFlags.Public)) {
enumValues.Add((int)Enum.Parse(e.GetType(), fi.Name, false));
}
return enumValues.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10305 次 |
| 最近记录: |