PropertyInfo.GetValue returns the name of the enumeration constant instead of the value

I am creating a serialization component that uses reflection to build serialized data, but I get weird results from the listed properties:

enum eDayFlags { Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64 } public eDayFlags DayFlags { get; set; } 

Now for the real test

 Obj Test = new Obj(); Test.DayFlags = eDayFlags.Friday; 

Serialization Result:

DayFlags = Friday

But if I set two flags in my variable:

 Obj Test = new Obj(); Test.DayFlags = eDayFlags.Friday; Test.DayFlags |= eDayFlags.Monday; 

Serialization Result:

Dayflags = 34

What I'm doing in the serialization component is pretty simple:

 //Loop each property of the object foreach (var prop in obj.GetType().GetProperties()) { //Get the value of the property var x = prop.GetValue(obj, null).ToString(); //Append it to the dictionnary encoded if (x == null) { Properties.Add(HttpUtility.UrlEncode(prop.Name) + "=null"); } else { Properties.Add(HttpUtility.UrlEncode(prop.Name) + "=" + HttpUtility.UrlEncode(x.ToString())); } } 

Can someone tell me how to get the real value of a variable from PropertyInfo.GetValue, even if this enumeration is only one value?

thanks

+4
source share
2 answers

You get real value - it's just converting to a string that does not do what you expect. The value returned by prop.GetValue will have the eDayFlags value in the box.

Do you want a numeric value from an enumeration? Drop it to int . You are allowed to unpack the enumeration value into its base type.

Note that your enumeration, which should probably be called Days , should have [Flags] attached to it, given that it is an enumeration of flags.

+4
source

This is the expected behavior.

You have not set the Flags attribute in your enum, so .ToString() returns a string representation of the enumeration listed as its base type ( int by default).

Adding [Flags] will force your .ToString() to return your expected value, i.e. "Monday, Friday"


If you decompile the Enum class, you will see code that looks like this in the implementation of ToString() :

 //// If [Flags] is NOT present if (!eT.IsDefined(typeof (FlagsAttribute), false)) //// Then returns the name associated with the value, OR the string rep. of the value //// if the value has no associated name (which is your actual case) return Enum.GetName((Type) eT, value) ?? value.ToString(); else //// [Flags] defined, so return the list of set flags with //// a ", " between return Enum.InternalFlagsFormat(eT, value); 
+1
source

All Articles