jeudi 23 février 2017

SetValue Method throw Exception when using reflection

I'm trying to set value to properties in many objects. I've a function that receive 2 parameters MyStructuredObjects and MyObject MyStructuredObjects has a list of MyObjects. This Function is a re-factory to remove a lot of 'if's.

I'd like to use ever the same object because the function it is used in a loop.If it is possible. I've getting ever the exception 'Object does not match target'. Sorry posting this, but I don't found problems like this, using List inside a Object structure.

Take a look :

public class MyStructuredObjects {
  public List<MyObject1> Object1{get;set;}
  public List<MyObject2> Object2{get;set;}
  public List<MyObject3> Object3{get;set;}
  public List<MyObject4> Object4{get;set;}
  public List<MyObject5> Object5{get;set;}
   }


 private void SetValuesToObjectsToIntegrate<T>(ref MyStructuredObjects returnedObject, T obj)
    {           
        Type t = obj.GetType();
        var propertyInfo = new ObjectsToIntegrate().GetType().GetProperties();
        var instance = Activator.CreateInstance(t);
        foreach (var item in returnedObject.GetType().GetProperties())
        {
            var itemType = item.PropertyType;
            if (t == itemType)      // PASSING BY HERE OK , it finds the same type :P
            {
                try
                {               

                    item.SetValue(instance , Convert.ChangeType(obj, item.PropertyType), null);

                }
                catch (Exception e)
                {

                }

            }
        }
    }

Thanks in advice !





Aucun commentaire:

Enregistrer un commentaire