C#-如何从静态对象创建动态对象? [英] C# - How to create a dynamic object from a static object?

查看:407
本文介绍了C#-如何从静态对象创建动态对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个静态对象,其类型为A.

Suppose there is a static object with type A.

class A
{
    public string b;
    public int c;
    public bool d;
    public A e;
    .
    .
    .
}

A a = new A(){
    b = "string",
    c = 12,
    d = true
    e = new A(){
            b = "another string",
            c = 23
        }
};

我想将该对象克隆到具有所有属性的dynamic对象中.

I want to deep clone this object into a dynamic object with all of its properties.

推荐答案

最简单的方法是将类序列化为json并将其反序列化为动态对象.

The easiest way is to serialize the class into a json and deserialize it into a dynamic object.

使用Json.net:

Use Json.net:

        A a = new A()
        {
            b = "string",
            c = 12,
            d = true,
            e = new A()
            {
                b = "another string",
                c = 23
            }
        };

        var json = JsonConvert.SerializeObject(a); // create a json 
        dynamic newObj = JsonConvert.DeserializeObject(json);// create a dynamic object

这篇关于C#-如何从静态对象创建动态对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆