如何传递枚举作为参数
可能的重复:
在 Silverlight 中迭代枚举?
我想出了一个方便的小函数让我得到枚举的计数(我知道它不能与所有枚举一起正常工作)。我不想将枚举硬编码到函数中,这样我就必须为要使用的每个枚举编写一个单独的函数,而是想将枚举作为参数传递,但我很难弄清楚如何做到这一点。
这是代码:
private enum MyColors { Red, Green, Blue }
private Int32 GetEnumCount()
{
Int32 i = 0;
while (Enum.IsDefined(typeof(MyColors), (MyColors)i))
{
i++;
}
return i;
}
更新
我最后想出了这个答案:
private Int32 GetEnumCount(Type enumType)
{
Int32 i = 0;
while (Enum.IsDefined(enumType, i))
{
i++;
}
return i;
}
Possible Duplicate:
Iterating through an enumeration in Silverlight?
I came up with a handy little function that gets me the count of an enum (I know it won't work properly with all enums). Rather than hard coding the Enum into the function such that I have to write a seprate function for each Enum I want to use it with, I wanted to pass the enum in as an argument but I am having difficulty figuring out how to do this.
Here is the code:
private enum MyColors { Red, Green, Blue }
private Int32 GetEnumCount()
{
Int32 i = 0;
while (Enum.IsDefined(typeof(MyColors), (MyColors)i))
{
i++;
}
return i;
}
UPDATE
I came up with this as the answer in the end:
private Int32 GetEnumCount(Type enumType)
{
Int32 i = 0;
while (Enum.IsDefined(enumType, i))
{
i++;
}
return i;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为替代方案(尽管显然这已经得到解答),如果您以 0 开始第一个,然后在末尾添加一个称为 count 的值,那么您可以使用它,例如:
As an alternative (although clearly this has already been answered) if you start the first one with 0 then add one on at the end called count then you can use that, eg:
这是可以完成的,但是需要一些额外的工作才能使其与不常用的枚举一起使用:
演示:http://ideone.com/塞尔吉
This can be done, but there's some additional work needed to make it work with unusal enums:
Demo: http://ideone.com/Serji
您应该将枚举
Type
作为参数,并删除对(MyColors)
的强制转换。在非 Sliverlight 中,您也可以将函数替换为
You should take the enum
Type
as an argument, and remove the cast to(MyColors)
.In non-Sliverlight, you can also just replace your function with