Holy reflection

I get the error "cannot convert string to int?". Which I find strange, I was under the concept, when you use PropertyInfo.SetValue , it should really try to use this type of field.

 // Sample: property.SetValue(model, null, null); 

The above will try to implement default(T) for the property according to PropertyInfo.SetValue for the Microsoft Developer Network. However, when I implement the following code:

 // Sample: property.SetValue(model, control.Value, null); 

Error when I implement string for a property that should have int? , I was under the notion that it will try to automatically resolve the specified type. How can I specify a type?

 // Sample: PropertyInfo[] properties = typeof(TModel).GetProperties(); foreach(var property in properties) if(typeof(TModel).Name.Contains("Sample")) property.SetValue(model, control.Value, null); 

Any clarifications and solutions to the throw will be helpful. The sample has been modified for brevity, trying to provide the appropriate code.

+5
source share
1 answer

You need to convert the control value to a type that uses the Convert.ChangeType() property:

 if(typeof(TModel).Name.Contains("Sample")) property.SetValue(model, Convert.ChangeType(control.Value, property.PropertyType), null); 

UPDATE:

In your case, this is a Nullable type ( Nullable<int> ), so you need to do it differently, since Convert.ChangeType() in normal mode does not work in Nullable types:

 if(typeof(TModel).Name.Contains("Sample")) { if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { property.SetValue(model,Convert.ChangeType(control.Value, property.PropertyType.GetGenericArguments()[0]),null); } else { property.SetValue(model, Convert.ChangeType(control.Value, property.PropertyType), null); } 
+3
source

All Articles