Set object properties with reflections

H

Horst Klein

I want set different properties of any object at runtime.
With the Function below it works well, but not perfect
Is there a way to set properties of any type with its value

Principle "one-line-code":
Dim propertyValue As Object = myPropertyType.Parse(GetType(myPropertyName),
myPropertyValue)
obj.GetType().GetProperty(myPropertyName).SetValue(obj, propertyValue,
Nothing)

Hardcode sample:
Dim propertyValue As Object = [Enum].Parse(GetType(FlatStyle),
propertyValue)
obj.GetType().GetProperty(propertyName).SetValue(obj, propertyValue,
Nothing)

I'm looking for a way to replace the Objecttypes "[Enum]" and "FlatStyle" by
an "generalobject"

How is this possible

Best regards Horst

'-----------------------------------------------------
Public Shared Sub SetPropertyValue(ByVal obj As Object, ByVal propertyName
As String, ByVal propertyValue As String)
Dim info As PropertyInfo = obj.GetType().GetProperty(propertyName,
BindingFlags.Instance Or BindingFlags.Public)
If (info Is Nothing) Then
LogFacade.LogWarning("Es gibt kein Property mit Namen " &
propertyName & " für die Klasse " & obj.GetType().Name & ".")
Else
Dim t As Type = info.PropertyType()
Dim o As Object
If (t.Equals(GetType(Boolean))) Then
o = Boolean.Parse(propertyValue.ToString())
ElseIf (t.Equals(GetType(Integer))) Then
o = Integer.Parse(propertyValue.ToString())
Else
o = propertyValue.ToString()
End If
info.SetValue(obj, o, Nothing)
End If
End Sub
'-----------------------------------------------------
 
H

Horst Klein

Found a solution:

Dim info As PropertyInfo = obj.GetType().GetProperty(propertyName,
BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.IgnoreCase)
If (info Is Nothing) Then
MessageBox.Show("Es gibt kein Property mit Namen " & propertyName & "
für die Klasse " & obj.GetType().Name & ".")
else
If info.CanRead And info.CanWrite Then
Dim newPropertyValue As Object
Dim t As Type = info.PropertyType()
Dim tc As TypeConverter = TypeDescriptor.GetConverter(t)
If(Not tc Is Nothing AndAlso tc.CanConvertFrom(GetType(String)))
Then
newPropertyValue = tc.ConvertFromInvariantString(propertyValue)
End If
info.SetValue(obj, newPropertyValue, Nothing)
End If
End If
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top