问题
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.
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);
}
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.
Thanks!
PS: Is it possible to change the contents of an enum at runtime? While the program is executing?
回答1:
Try this:
public int countElements(Type type)
{
if (!type.IsEnum)
throw new InvalidOperationException();
return Enum.GetNames(type).Length;
}
public void foo()
{
int num = countElements(typeof(ELEMENT));
}
回答2:
You could also do this with a generic method. Personally I like the syntax better for the foo()
method this way, since you don't have to specify typeof()
// Counts how many different members exist in the enum type
public int countElements<T>()
{
if(!typeof(T).IsEnum)
throw new InvalidOperationException("T must be an Enum");
return Enum.GetNames(typeof(T)).Length;
}
// Call above function
public void foo()
{
int num = countElements<ELEMENT>();
}
来源:https://stackoverflow.com/questions/10021249/passing-an-enum-as-an-argument