I am trying to dynamically assign values to properties using reflection. It works fine unless a property is defined as an enum. When I try to conevrt the value to the expected type...I get a casting error... Here is the code... Any thoughts? A better way perhaps?
Imports System.Reflection
Module Module2
Sub Main()
Dim class1 As Class1 = New Class1
Console.WriteLine(class1.test1)
SetProperty(class1, "test1", "testing")
Console.WriteLine(class1.test1)
Console.WriteLine(class1.test2)
SetProperty(class1, "test2", "1")
Console.WriteLine(class1.test2)
Console.ReadLine()
End Sub
End Module
Public Class Class1
Private _test1 As String = "test"
Public Property test1() As String
Get
Return _test1
End Get
Set(ByVal Value As String)
_test1 = Value
End Set
End Property
Private _test2 As TestEnum = TestEnum.Test0
Public Property test2() As TestEnum
Get
Return _test2
End Get
Set(ByVal Value As TestEnum)
_test2 = Value
End Set
End Property
Public Enum TestEnum As Integer
Test0 = 0
Test1 = 1
End Enum
Function SetProperty(ByVal obj As Object, ByVal propertyName As String, _
ByVal val As Object) As Boolean
Dim pi As System.Reflection.PropertyInfo = obj.GetType().GetProperty(propertyName)
Try
' get a reference to the PropertyInfo, exit if no property with that
' name
If pi Is Nothing Then
Return False
End If
' convert the value to the expected type
val = Convert.ChangeType(val, pi.PropertyType)
' attempt the assignment
pi.SetValue(obj, val, Nothing)
Return True
Catch
Return False
End Try
End Function
End Class