标签云

微信群

扫码加入我们

WeChat QR Code

This question already has an answer here:How do I enumerate an enum in C#?26 answerspublic enum Foos{A,B,C}Is there a way to loop through the possible values of Foos?Basically?foreach(Foo in Foos)


You can cast the array directly: (T[])Enum.GetValues(typeof(T))

2019年06月25日31分55秒

The good thing about ŞafakGür's comment is that (1) you don't have to go through an extra iterator (.Cast<Foos>), and (2) you don't need to box all the values and unbox them again. Şafak's cast will remain valid as long as they don't change the array type returned to some other type (like object[]). But we can be completely sure they won't because (a) it would lose performance, (b) there are already millions of codelines using Şafak's cast, and they would all break with a runtime exception.

2019年06月25日31分55秒

Of course, how many enums are going to contain more than a dozen or two values? I imagine that in most cases boxing/unboxing is a negligible hit, so the cleanest solution is the highest priority.

2019年06月25日31分55秒

JCoombs I find this clean enough: public static IReadOnlyList<T> GetValues<T>() { return (T[])Enum.GetValues(typeof(T)); }. But yeah, performance difference is negligible in common usage. I just don't like the idea of creating an iterator when I already have an iterable (enumerable) object to return.

2019年06月26日31分55秒

Unfortunately, this does not answer the question posed. The question was how to loop through the values of an enum. SLaks answered the question.

2019年06月26日31分55秒

This is a great solution.By using "Foos" instead of "var" the type inference system was able to use the right version of GetValues which returned the correct object type. Nice!

2019年06月26日31分55秒

RobertPatterson By using Foos nothing is magically inferred. It is an explicit cast.

2019年06月25日31分55秒

daveD I'd like to think people can handle writing a foreach block on their own.

2019年06月25日31分55秒

RobertPatterson var works here, in 2019.

2019年06月25日31分55秒

Why is using LINQ "more correct"? Please c.f. You can cast the array directly: (T[])Enum.GetValues(typeof(T)) SafakGür, this version has less overhead IMO.

2019年06月25日31分55秒

make it simple GetEnumValues<T>() where T : Enum

2019年06月25日31分55秒

SaboorAwan is not possible to use System.Enum as a type parameter constraint. Compiler says: Constraint cannot be special class 'Enum'

2019年06月26日31分55秒

Yes that's why I have that comment and type checking thing in my implementation; I'd already thought of that. :)

2019年06月25日31分55秒

Quick note. In C# 7.3 you can now use Enum (as well as unmanaged and delegate) as generic constraints.

2019年06月25日31分55秒