I already found out that it is possible to set the value of a property using reflection: Set object property using reflection
But my problem is that my data exists only as string. Therefore of course I always get an exception because it is not the right type.
Is there a way of automatically trying to parse the string to the according type (DateTime, int, decimal, float)?
Below is the code I'm using:
Type myType = obj.GetType();
PropertyInfo[] props = myType.GetProperties();
foreach (PropertyInfo prop in props)
{
setProperty(obj, prop, data[prop.Name]);
}
data
is a simple associative array that contains the data as string. These data are supposed to be mapped into obj
.
To set property values via Reflection, you must use the Type. GetProperty() method, then invoke the PropertyInfo. SetValue() method. The default overload that we used accepts the object in which to set the property value, the value itself, and an object array, which in our example is null.
To set the value of an indexed property, call the SetValue(Object, Object, Object[]) overload. If the property type of this PropertyInfo object is a value type and value is null , the property will be set to the default value for that type.
Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.
GetProperty(String, BindingFlags) Searches for the specified property, using the specified binding constraints. public: virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, System::Reflection::BindingFlags bindingAttr); C# Copy.
You can use the Convert
class:
var value = Convert.ChangeType(data[prop.Name], prop.PropertyType);
setProperty(obj, prop, value);
You should be able to use the TypeConverter
:
var converter = TypeDescriptor.GetConverter(prop.PropertyType);
var value = converter.ConvertFromString(data[prop.Name]);
setProperty(obj,prop,value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With