通过Silverlight中的枚举进行迭代?

eri*_*200 31 silverlight

在.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)

  • 这个解决方案有点不尽如人意.使用语法要求您提供枚举类型的实例,而原始的.net方法允许您直接处理类型.在这方面,我更好地找到了@ptoinson的答案.它的语法简单而干净.GetEnumValues <MyEnumType>() (3认同)
  • 您可以通过获取基础类型(Enum.GetUnderlyingType())来支持非int类型 (2认同)