【问题标题】:How to return a string[] containing values of an Enum如何返回包含枚举值的字符串 []
【发布时间】:2013-01-10 22:00:10
【问题描述】:

我想创建一个动态 GUI,将 Enum 的所有选项列为按钮。因此,我需要一种将 Enum 类型传递给方法并取回包含 enum 类型可以是的所有选项的字符串数组的方法。

例如,给定文件 Foo.cs 中的 Enum 声明:

public Enum Fruits {
    Apple,
    Orange,
    Peach
};

public class Foo { ... }

我想要这个返回:

{ "Apple", "Orange", "Peach" }

我经历了几次代码排列。现在我有以下但我收到一个错误“找不到类型或命名空间名称'enumeratedType'

public static string[] EnumToStringArray (System.Type enumeratedType) {
    int         enumSize    =   sizeof(enumeratedType);
    string[]    enumStrings =   new string[enumSize];

    for (int i = 0 ; i < enumSize ; i++) {
        enumStrings[i]  =   enumeratedType.getValues()[i].toString();
    }

    return enumStrings;
}

我正在尝试做的事情可能吗?我已经根据这个问题Using sentinal values in C# enum (size of enum at compile time)? 中的信息尝试了几次完整的重写,但我无法让它工作。

【问题讨论】:

  • Enum.GetNames(typeof (Fruits));
  • 这可能是使用反射和PropertInfo 类列出事物的情况
  • 酷,谢谢亚历山大!完美答案!

标签: c# arrays string enums namespaces


【解决方案1】:
string[] names = Enum.GetNames(typeof(Fruits));

【讨论】:

    【解决方案2】:

    你可以使用类似的东西

    public static IEnumerable<string> EnumToStringArray(Type enumeratedType) {
        if (!enumeratedType.IsEnum)
            throw new ArgumentException("Must be an Enum", "enumeratedType");
    
        return Enum.GetNames(enumeratedType);
    }
    

    但即使这样也是不必要的,因为如果给定类型不是 EnumEnum.GetNames(...) 本身会抛出 ArgumentException。 (感谢@Alexander Balte)。 因此,无论如何您都不需要自己的功能。正如其他人已经提到的那样,只需 Enum.GetNames(typeof(Fruits)) 就可以完成这项工作。

    【讨论】:

    • 如果enumeratedType 不是枚举,Enum.GetNames 无论如何都会抛出ArgumentException。我认为没有理由检查 enumeratedType.IsEnum 并抛出 ArgumentException
    • 谢谢,我已经更新了我的答案以供参考,以防其他人这样做也比必要的复杂。
    【解决方案3】:

    您似乎误解了sizeof keyword 的含义。它返回值类型在与非托管内存中的其他值对齐时“占用”的字节数(每个字节等于 8 位)。

    如果您不使用unsafe 上下文(如指针),sizeof 将没有用处。

    对于您的 Fruits 类型,sizeof(Fruits) 返回 4,因为底层的迭代器类型是 Int32(因为这是您未另行指定时的默认值)。 Int32 需要 32 位,因此 sizeof 返回 4。不管你有 1、2、10 还是 4294967296 种不同的水果。

    请注意,一个枚举可以有多个名称指向同一个值,例如:

    public enum Fruits {
      Apple,
      Orange,
      Peach,
      ChineseApple = Orange,
    }
    

    在此示例中,枚举包含四个命名常量,但其中两个“映射到”相同的值。在这种情况下,Enum.GetNames(typeof(Fruits)) 将为您提供所有四个名称。

    但是Enum.GetValues(typeof(Fruit)) 会给你一个Fruit 的四个的列表,其中两个是相同的。您无法提前知道这两个相同的值是否会显示为OrangeChineseApple,因此如果您的枚举有类似的重复项,请不要使用此方法。

    【讨论】:

      猜你喜欢
      • 2012-04-25
      • 1970-01-01
      • 2021-05-18
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      相关资源
      最近更新 更多