本文介绍了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#-如何从静态对象创建动态对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!