mardi 7 juin 2016

Reflection: Set properties of basetype

I want to use Reflection to convert a KeyValuePair to different Properties of an object. These Properties can be simple Types or Complex types. If they are properties of the "BaseClass" type I want to assign the Id and Name:

My Classes:

public class MyBaseClass {
  public int Id { get;set;}
  public string Name {get; set;}
}

public class Person:MyBaseClass {
  public int Age {get;set;}
}

public class Item:MyBaseClass {
  public decimal Price {get;set;}
}

public class TargetClass {
  public Person Chief {get;set;}
  public Item Product {get;set;}
}

Now I want to use Reflection to assign the values:

foreach (var field in Fields) {
    var target=targetType.GetProperty(field.Key);
    if (field.Value.indexOf("|")>0) {
       int id=int.Parse(field.Value.Split('|')[0]);
       string name=field.Value.Split('|')[1];
       var baseObj = new MyBaseClass { Id = id, Name=name };
       target.SetValue(dest, baseObj);
    } else {
       target.SetValue(dest,field.Value);
    }
}

So if the field contains a "|" I want to split that value in an Id and a Title and Assign them to the target type.

Fields is a Dictionary of targetType is typeof(TargetClass) and dest is an object of TargetClass.

So in my example, target could be the Property Chief and field["Chief"] could be "23|John Doe"

But when I try to assign an object of MyBaseClass to the Property Chief(or Product) I receive an error that the conversion from MyBaseClass to Chief failed. But to use this in a generic fashion I do want to use this method on any Object that is derived from MyBaseClass.





Aucun commentaire:

Enregistrer un commentaire