enumerations & reflection

  • Thread starter Thread starter Mordachai
  • Start date Start date
M

Mordachai

I'm trying to simply generate the list of enumeration values for a given
enumeration class.

e.g., for the following:

enum struct Colors { red, green, blue };

I would like to have a function:

void PrintValuesOf(the enumeration class or instance or whatever works)
{
for each (value in the given enumeration)
Console::WriteLine(the name of the enumeration & its value);
}

Which would output:

red
green
blue

Thanks for any assistence!

--


Steven S. Wolf
Head of Software Development
Cimex Corporation
 
Mordachai said:
I'm trying to simply generate the list of enumeration values for a given
enumeration class.

e.g., for the following:

enum struct Colors { red, green, blue };

I would like to have a function:

void PrintValuesOf(the enumeration class or instance or whatever works)
{
for each (value in the given enumeration)
Console::WriteLine(the name of the enumeration & its value);
}

Which would output:

red
green
blue

Thanks for any assistence!

Something like this -

<code>
using namespace System;
using namespace System::Reflection;

public enum struct Colors { red, green, blue };

void PrintValuesOf(Type^ enumType)
{
if (!enumType->IsEnum)
return;
for each (MemberInfo^ mi in
enumType->GetMembers(BindingFlags::Static|BindingFlags::Public))
{
if (mi->MemberType != MemberTypes::Field)
continue;
Console::WriteLine("Name: {0} Value:
{1}",mi->Name,(int)Enum::Parse(enumType,mi->Name));
}
}

void main()
{
PrintValuesOf(Colors::typeid);
}

</code>

There might be a better way to get the value associated with a given member
name than using Enum.Parse, but if there is, I didn't find it.

-cd
 
Back
Top