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
.
It doesn't work because you try to assign instance of a base class ( MyBaseClass
) to the property which expects instance of child class ( Person
). If you can be sure that all classes inherited from MyBaseClass
has parameterless public constructor - create new instance of expected type via reflection and cast it to MyBaseClass
:
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 = (MyBaseClass) Activator.CreateInstance(target.PropertyType);
baseObj.Id = id;
baseObj.Name = name;
target.SetValue(dest, baseObj);
} else {
target.SetValue(dest,field.Value);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.