问题描述
我正在尝试制作一个简单的Roguelike游戏,以更好地学习C#.我试图做一个通用方法,可以给它一个Enum作为参数,它将以整数形式返回该Enum中有多少个元素.我需要使其尽可能通用,因为我将有几个不同的类来调用该方法.
I am playing around with trying to make a simple Roguelike game to learn C# a bit better. I am trying to make a general method that I can give it an Enum as an argument, and it will return how many elements are in that Enum as an int. I need to make it as general as possible, because I will have several different classes calling the method.
我已经搜索了最后一个小时左右,但是我在这里找不到任何资源,否则就完全可以回答我的问题了……我仍然处于C#的初学者中级阶段,所以我仍然学习事物的所有语法,但是到目前为止,这是我所拥有的:
I have searched around for the last hour or so, but I couldn't find any resources here or otherwise that quite answered my question... I'm still at a beginner-intermediate stage for C#, so I am still learning all the syntax for things, but here is what I have so far:
// Type of element
public enum ELEMENT
{
FIRE, WATER, AIR, EARTH
}
// Counts how many different members exist in the enum type
public int countElements(Enum e)
{
return Enum.GetNames(e.GetType()).Length;
}
// Call above function
public void foo()
{
int num = countElements(ELEMENT);
}
它编译时出现错误参数1:无法从'System.Type'转换为'System.Enum'".我有点明白为什么它不起作用,但我只需要一些指导即可正确设置所有内容.
It compiles with the error "Argument 1: Cannot convert from 'System.Type' to 'System.Enum'". I kind of see why it won't work but I just need some direction to set everything up correctly.
谢谢!
PS:是否可以在运行时更改枚举的内容?在程序执行期间?
PS: Is it possible to change the contents of an enum at runtime? While the program is executing?
推荐答案
尝试一下:
public int countElements(Type type)
{
if (!type.IsEnum)
throw new InvalidOperationException();
return Enum.GetNames(type).Length;
}
public void foo()
{
int num = countElements(typeof(ELEMENT));
}
这篇关于将枚举作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!