Kyl*_*ran 3 c# parameters types enumeration
我正在尝试制作一个简单的Roguelike游戏,以便更好地学习C#.我试图制作一个通用的方法,我可以给它一个Enum作为参数,它将返回该枚举中有多少元素作为int.我需要让它尽可能通用,因为我将有几个不同的类调用该方法.
我在最后一个小时左右搜索了一下,但是我找不到任何资源或者其他方式完全回答了我的问题...我仍然处于C#的初级中级阶段,所以我仍在学习所有的事物的语法,但这是我到目前为止:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
它编译时出现错误"Argument 1:无法从'System.Type'转换为'System.Enum'".我有点明白为什么它不起作用,但我只需要一些方向来正确设置一切.
谢谢!
PS:是否可以在运行时更改枚举的内容?程序正在执行?
试试这个:
public int countElements(Type type)
{
if (!type.IsEnum)
throw new InvalidOperationException();
return Enum.GetNames(type).Length;
}
public void foo()
{
int num = countElements(typeof(ELEMENT));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6242 次 |
最近记录: |