Is there an easy way to copy everything from a strongly typed object into a dynamic one? The target has to be a DynamicObject
as determined by a 3rd party library I'm using. Everything from TypedModel
needs to go into MyDynamicObject
at runtime.
public class MyDynamicObject : DynamicThirdPartyObject
{ }
public class TypedModel
{
public string text { get; set; }
public int number { get; set; }
public List<SomeOtherModel> someList { get; set; }
}
Existing solutions I found on SO all match up properties between typed classes.
EDIT
Found a simple solution based on FastMember
:
public void CopyProperties(object source, DynamicObject target)
{
var wrapped = ObjectAccessor.Create(target);
foreach (var prop in source.GetType().GetProperties())
{
wrapped[prop.Name] = prop.GetValue(source);
}
}
I propoes to use reflection.
suppose you make following declaration:
public class MyDynamicObject : DynamicThirdPartyObject
{ }
public class TypedModel
{
public string text { get; set; }
public int number { get; set; }
public List<SomeOtherModel> ListOtherModel { get; set; }
}
Lets say you want to get properties of instance:
typedModel.GetType().GetProperties();
Another possible situation is if you want to copy type:
typeof(TypedModel).GetProperties();
TypedModel typeModel = new TypedModel {number = 1, text = "text1",
ListOhterModel = new List()
};
foreach(var prop in typeModel.GetType().GetProperties())
{
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(typeModel, null));
}
And if you need to go through hierarchy, maybe you need to use recursion, in order to go through nested types, I mean you can use reflection for copying all members of SomeOtherModel.
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.