简体   繁体   English

将强类型对象的所有属性复制到DynamicObject中

[英]Copy all properties of strongly typed object into DynamicObject

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. 目标必须是由我使用的第三方库确定的DynamicObject Everything from TypedModel needs to go into MyDynamicObject at runtime. TypedModel所有内容都需要在运行时放入MyDynamicObject中。

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. 我在SO上发现的现有解决方案都可以在类型化类之间匹配属性。

EDIT 编辑

Found a simple solution based on FastMember : 找到了一个基于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. 而且,如果需要遍历层次结构,也许需要使用递归,以便遍历嵌套类型,我的意思是可以使用反射来复制SomeOtherModel的所有成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM