I managed to get the value of an enum via reflection. I have to use reflection since I have different objects with enums in them.
But how do I get the name of the enum?
Let's say I have
enum MyEnum
{
A,
B
}
I can get if (strValue.Equals("A"))
as a result, but how do I get if (strName.Equals("MyEnum"))
?
I do have to mention that the enums are nullable!
To be more specific this is the method I want to use:
static void DumpProperties(object the_object)
{
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("test.txt", true);
System.Reflection.PropertyInfo[] properties = the_object.GetType().GetProperties();
file.WriteLine("//");
file.WriteLine("//{0} -----------------", the_object.GetType().Name);
foreach (System.Reflection.PropertyInfo property in properties)
{
Type prop_type = property.PropertyType;
string val = "";
if (
(prop_type == typeof(int))
|| (prop_type == typeof(string))
|| (prop_type == typeof(bool))
|| (prop_type == typeof(float))
|| (prop_type == typeof(double))
|| (prop_type == typeof(UInt32))
|| (prop_type == typeof(UInt64))
|| (prop_type == typeof(UInt32))
|| (prop_type == typeof(UInt16))
|| (prop_type == typeof(System.DateTime))
|| (prop_type == typeof(int?))
|| (prop_type == typeof(bool?))
|| (prop_type == typeof(float?))
|| (prop_type == typeof(double?))
|| (prop_type == typeof(UInt32?))
|| (prop_type == typeof(UInt64?))
|| (prop_type == typeof(UInt32?))
|| (prop_type == typeof(UInt16?))
|| (prop_type == typeof(System.DateTime?))
)
{
object obj_val = property.GetValue(the_object, null);
if (obj_val == null)
{
val = "null";
}
else
{
if (prop_type == typeof(string))
val = string.Format("\"{0}\"", obj_val.ToString());
else
val = string.Format("{0}", obj_val.ToString());
}
}
else if ((prop_type.IsEnum)
|| (IsNullableEnum(prop_type)))
{
object obj_val = property.GetValue(the_object, null);
if (obj_val == null)
{
val = "null";
}
else
{
val = string.Format("{0}.{1}", prop_type.GetType(), obj_val.ToString());
}
}
else
{
object obj_val = property.GetValue(the_object, null);
if (obj_val == null)
{
val = "null";
}
else
{
val = string.Format("{0}", obj_val.ToString());
}
}
if (!val.Equals("null"))
file.WriteLine("pstyleHeading.{0} = {1};", property.Name, val);
}
file.Close();
}
public static bool IsNullableEnum(Type t)
{
Type u = Nullable.GetUnderlyingType(t);
return (u != null) && u.IsEnum;
}
The problem is at line 58. prop_type.GetType()
is wrong, but I cannot figure out what it should be...