Set an Enum property using reflection?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Is there any way to set the value of a property that has been declared as an Enum type using reflection

Basically I'm trying to write a generic procedure that will parse through an XML node and set any matching properties of an object passed in to the corresponding values. This works great for any of the primitive types, but i cannot get it to work if the property is an enum. I've found that using reflection I can loop through the static fields of the Enum type and if the value of one corresponds to the value I am trying to set I can use the GetValue on the FieldInfo object to set the value, but this does not work if the value is two or more of the Enum values OR'd together

In the example here, the PropertyInfo.SetValue call will die with an "Object type cannot be converted to target type" error. Is there any way to do a conversion on the value so that it will be accepted


Private Sub Form1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.DoubleClic
Dim oObject As New claMyClas

claReflection.SetPropertyViaReflection(oObject
End Su

Public Class claMyClas
Private meAnchor As AnchorStyle

Public Property Anchor() As AnchorStyle
Ge
Return meAncho
End Ge
Set(ByVal eAnchor As AnchorStyles
meAnchor = eAncho
End Se
End Propert
End Clas

Public Class claReflectio
Public Shared Sub SetPropertyViaReflection(ByVal oObject As Object
Dim sPropertyName As String = "Anchor
Dim iValue As Int32 =

Dim oPropertyInfo As Reflection.PropertyInfo = oObject.GetType.GetProperty(sPropertyName

oPropertyInfo.SetValue(oObject, iValue, Nothing

End Su
End Class
 
Is there any way to do a conversion on the value so that it will be accepted?

Dim oValue As Object = [Enum].Parse(oPropertyInfo.PropertyType,
iValue.ToString())
oPropertyInfo.SetValue(oObject, oValue, Nothing)



Mattias
 
Thank Mattias,

Turns out what I was looking for was similar to your suggestion....

oPropertyInfo.SetValue(oObject, System.Enum.ToObject(oPropertyInfo.PropertyType, oValue), Nothing)
 
Back
Top