samedi 7 mars 2015

C#-Reflection-Setvalue -An unhandled exception of type 'System.Reflection.TargetException' occurred in mscorlib.dll

Consider this code



public object ApplyChanges(object existObject, IEnumerable<ChangeEvent<T>> Eventslist)
{

if (existObject == null) return null ;
Type objectType = typeof(T);
var proerties = objectType.GetProperties();

foreach (var items in Eventslist)
{
var property = proerties.FirstOrDefault(x => x.Name.ToLower() == items.Field.ToLower());
if (property != null)
{
var ptype = property.GetType();
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var underlyingType = Nullable.GetUnderlyingType(property.PropertyType);
var underlyType = Convert.ChangeType(items.Value, underlyingType);
var converter = new NullableConverter(property.PropertyType);
var data = converter.ConvertFrom(underlyType);
property.SetValue(existObject, data);
}
else
{
var Newtype = Convert.ChangeType(items.Value, property.PropertyType);
property.SetValue(existObject, Newtype);//this line I have an exception
}
}
}
return existObject;

}


I am getting the error in the else part in setvalue method. The existObject contains collection of records from different tables.I have already checked both property types(the property inside object and the Newtype variable)both of them are object {string} !!






Aucun commentaire:

Enregistrer un commentaire