C#:枚举值的通用列表
有没有办法创建一个方法,该方法获取枚举类型作为参数,并从其值返回枚举基础类型的通用列表,无论基础类型是否为 int\short byte 等'...
我看到了乔恩·斯基特的这个答案,但看起来好像是这样太复杂了。
Is there a way to create a method that gets an enum type as a parameter, and returns a generic list of the enum underlying type from it's values, no matter if the underlying type is int\short byte etc'...
I saw this answer of Jon Skeet, but it looks way too complicated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想传递
类型
,它实际上不能是有用的泛型 - 您必须返回一个与输入不直接相关的类型 ,因此类似于:这是底层的强类型向量,因此您可以将其转换为
int[]
等。If you want to pass in a
Type
, it can't really be usefully generic - you'd have to return a single type that isn't directly related to the input, hence something like:This is a strongly-typed vector underneath, so you could cast that to
int[]
etc.虽然马克的回答没有错,但有些不必要。
Enum.GetValues(type)
返回一个TEnum[]
所以这个方法是不必要的,就好像你知道底层类型,你可以直接转换TEnum[]< /code> 为其基础类型数组。
是有效的 C#,可以编译并且在运行时不会抛出异常。由于您在拥有数组后想要一个列表,因此可以将其传递给
List
构造函数,或者您也可以只调用ToArray()
扩展方法。编辑:您可以这样编写函数::
但是您必须首先知道底层类型。
While Marc's answer isn't wrong its somewhat unnecessary.
Enum.GetValues(type)
returns aTEnum[]
so this method is kind of unnecessary as if you know the underlying type you can just castTEnum[]
to its underlying type array.is valid C# that will compile and won't throw an exception at runtime. Since you wanted a list once you have the array you can pass it to the
List<Tunderlying>
constructor or you can just call theToArray()
extension method.Edit: you could write the function as such::
But then you would have to know the underlying type first.