迭代枚举类型

发布于 2024-11-29 00:16:39 字数 515 浏览 3 评论 0原文

可能的重复:
如何枚举枚举?

我不知道是否可能做我想做的事,但我想为什么不呢。

我有示例枚举:

public enum Animals {
    Cat,
    Dog,
    ...
}

我想做的是迭代这个枚举。我希望它像这样工作:

foreach( var type in Animals ) {
    Console.WriteLine( type.toString() );
}

输出将是:

 Cat
 Dog

这可能吗?我不想将每个项目放入数组中,然后进行迭代,我想直接迭代这个枚举。

Possible Duplicate:
How do I enumerate an enum?

I don't know if it is possible to do what I want to do, but I think why not.

I have example enum:

public enum Animals {
    Cat,
    Dog,
    ...
}

What I want to do is to iterate on this enum. I want it work like that:

foreach( var type in Animals ) {
    Console.WriteLine( type.toString() );
}

and the output will be:

 Cat
 Dog

Is it possible? I don't want to put every item to an array, and then iterate, I want to iterate directly on this enum.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

久夏青 2024-12-06 00:16:39

编辑:请注意,在整个答案中,我已将 Animals 重命名为 Animal。根据 .NET 约定,只有基于标志的枚举才应具有复数名称。

您可以使用 Enum.GetValues()

foreach (var type in (Animal[]) Enum.GetValues(typeof(Animal)) {
    Console.WriteLine(type.toString());
}

正如 Dan 的评论中所述,如果您在 foreach 循环中使用显式类型,则不需要强制转换:

foreach (Animal type in Enum.GetValues(typeof(Animal)) {
    Console.WriteLine(type.toString());
}

但现在您将无法尽早发现错误。例如:

foreach (Animal type in Enum.GetValues(typeof(SomeEmptyEnum)) {
    Console.WriteLine(type.toString());
}

其中 SomeEmptyEnum 是(显然)一个空枚举类型。这里 GetValues 将返回 SomeEmptyEnum[] 类型的空数组。上面的代码只会检查返回数组的每个成员的类型是否正确,因此您不会发现问题。显然,这在现实生活中不太可能发生,但它展示了某种代码味道,导致我转而转换结果 - 基本上我更喜欢处理强类型集合。


或者,如果需要更安全的方法,您可以使用我的 Unconstrained Melody 库:

foreach (var type in Enums.GetValues<Animal>()) {
    Console.WriteLine(type.ToString());
}

这里是我的 Enums .GetValues() 返回一个 IList,这意味着:

  • 不需要强制转换
  • 它实际上返回一个不可变列表,因此它不需要每次都创建一个新集合,与标准 Enum.GetValues() 不同,

它还有一个通用约束强制 T 为枚举类型,因此您不会意外地使用非枚举类型调用它,这与 Enum.GetValues() 不同...

EDIT: Note that throughout this answer I've renamed Animals to Animal. According to .NET conventions, only flags-based enums should have a plural name.

You can use Enum.GetValues():

foreach (var type in (Animal[]) Enum.GetValues(typeof(Animal)) {
    Console.WriteLine(type.toString());
}

As noted in Dan's comment, if you use explicit typing in your foreach loop, you don't need to cast:

foreach (Animal type in Enum.GetValues(typeof(Animal)) {
    Console.WriteLine(type.toString());
}

But now you won't spot errors as early as you could. For example:

foreach (Animal type in Enum.GetValues(typeof(SomeEmptyEnum)) {
    Console.WriteLine(type.toString());
}

Where SomeEmptyEnum is (obviously) an empty enum type. Here GetValues will return an empty array of type SomeEmptyEnum[]. The code above will only check that each member of the returned array is of the right type, so you won't spot the problem. Obviously this is unlikely to happen in real life, but it demonstrates the sort of code smell which leads me to cast the result instead - basically I far prefer dealing with strongly-typed collections.


Alternatively, for a somewhat more typesafe approach, you can use my Unconstrained Melody library:

foreach (var type in Enums.GetValues<Animal>()) {
    Console.WriteLine(type.ToString());
}

Here my Enums.GetValues<T>() returns an IList<T>, which means:

  • There's no need to cast
  • It actually returns an immutable list, so it doesn't need to create a new collection each time, unlike the standard Enum.GetValues()

It's also got a generic constraint forcing T to be an enum type, so you can't accidentally call it with a non-enum type, unlike Enum.GetValues()...

放血 2024-12-06 00:16:39

Enum.GetValues 是您的朋友。

Enum.GetValues is your friend.

我偏爱纯白色 2024-12-06 00:16:39

使用 Enum.GetNames() 循环访问名称您的枚举成员的数量。使用 Enum.GetValues() 循环访问值。

Use Enum.GetNames() to loop through the names of the members of your enumeration. Use Enum.GetValues() to loop through the values.

谜兔 2024-12-06 00:16:39

试试这个:

    enum animals
    {
        cat,
        dog,
        fish
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (string myAnimal in Enum.GetNames(typeof(animals)))
        {
            Debug.WriteLine(myAnimal);
        }
    }

您必须迭代 Enum.Getnames(typeof(yourEnum))。

祝你好运。

Try this:

    enum animals
    {
        cat,
        dog,
        fish
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (string myAnimal in Enum.GetNames(typeof(animals)))
        {
            Debug.WriteLine(myAnimal);
        }
    }

You have to iterate through the Enum.Getnames(typeof(yourEnum)).

Good luck.

虫児飞 2024-12-06 00:16:39

要节省在 Jon 的答案中的一些输入,请明确指定类型,然后您就不会t 必须强制转换:

foreach (Animal a in Enum.GetValues(typeof(Animal)) {
    Console.WriteLine(a);
}

但是,这也需要额外小心,因为 乔恩解释

另请注意,C# 枚举名称通常应采用单数形式(Animal,而不是 Animals),除非它们用 [Flags] 属性标记允许组合。

To save some typing in Jon's answer, specify the type explicitly and you won't have to cast:

foreach (Animal a in Enum.GetValues(typeof(Animal)) {
    Console.WriteLine(a);
}

However this would also need additional caution as explained by Jon.

Also note that C# enum names should usually be in singular form (Animal, not Animals), unless they are marked with [Flags] attribute which allows combinations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文