I want to use reflection to set some fields according to data from a file. The information that I can have is TypeName, TypeValue and FieldName.
While this is trivial on classes (Activator.CreateInstance and PropertyInfo.SetValue), I am a bit dumbstruck when it comes to value types like Int32 which does not have any properties. I see that IsValueType is true on those Types, but as my TypeValue is a string (i.e. string TypeValue = "400"), I don't know how to assign it.
Do I have to use GetMethods()
to check if there is a .Parse Method? Is this something for a TypeConverter
?
I know I could just hardcode some common value types (there aren't that many anyway) and have a big switch() statement, but I wonder if there is something that automagically does a "Convert String to T" conversion?
// get the type converters we need
TypeConverter myConverter = TypeDescriptor.GetConverter(typeof(int));
// get the degrees, minutes and seconds value
int Degrees = (int)myConverter.ConvertFromString(strVal);
this should help
ArsenMkrt is right; TypeConverter
is the way to go here; some extra thoughts, though:
You might consider using "component model" rather than reflection; i.e. instead of typeof(T).GetProperties()
, consider TypeDescriptor.GetProperties(typeof(T))
. This gives you a set of PropertyDescriptor
records instead of the reflection PropertyInfo
. Why is this handy?
prop.Converter
on PropertyDescriptor
HyperDescriptor
As an example of a property with custom converter:
[TypeConverter(typeof(CurrencyConverter))] // bespoke
public decimal TotalPrice {get;set;}
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