[英]Serialize dynamic object into a class file
有没有办法将动态 object 序列化为 class 定义?
例如:
dynamic test = new System.Dynamic.ExpandoObject();
test.property1 = "test";
test.property2 = 123;
至
public class test
{
string property1;
int property2;
}
你可以像这样制作一个运行时代码生成器,尽管我不确定这是否是你想要做的?
public static string GenerateClass(string className, ExpandoObject eObj)
{
var sb = new StringBuilder();
sb.Append("public class ");
sb.Append(className);
sb.AppendLine();
sb.Append("{");
sb.AppendLine();
foreach (var property in (IDictionary<String, Object>)eObj)
{
sb.Append(" ");
sb.Append(property.Value.GetType());
sb.Append(" ");
sb.Append(property.Key);
sb.Append(" ");
sb.Append("{ get; set; }");
sb.AppendLine();
}
sb.Append("}");
sb.AppendLine();
return sb.ToString();
}
传递您的 expando object 返回:
public class test
{
System.String property1 { get; set; }
System.Int32 property2 { get; set; }
}
用法:
static void Main(string[] args)
{
dynamic test = new System.Dynamic.ExpandoObject();
test.property1 = "test";
test.property2 = 123;
Console.WriteLine(GenerateClass("test", (ExpandoObject)test));
}
**编辑:对于嵌套类型,您可以这样做:**
public static string GenerateClass(string className, ExpandoObject eObj)
{
var sb = new StringBuilder();
sb.Append("public class ");
sb.Append(className);
sb.AppendLine();
sb.Append("{");
sb.AppendLine();
foreach (var property in (IDictionary<String, Object>)eObj)
{
string typeName = property.Value.GetType().Name;
if (property.Value is ExpandoObject nestedEObj)
{
typeName = property.Key;
sb.AppendLine();
foreach (string nestedClassLine in GenerateClass(property.Key, nestedEObj).Split(Environment.NewLine))
{
sb.Append(" ");
sb.Append(nestedClassLine);
sb.AppendLine();
}
}
sb.Append(" ");
sb.Append(typeName);
sb.Append(" ");
sb.Append(property.Key);
sb.Append(" ");
sb.Append("{ get; set; }");
sb.AppendLine();
}
sb.Append("}");
sb.AppendLine();
return sb.ToString();
}
用法:
static void Main(string[] args)
{
dynamic test = new System.Dynamic.ExpandoObject();
test.property1 = "test";
test.property2 = 123;
dynamic nest = new System.Dynamic.ExpandoObject();
nest.property1 = "testForNest";
nest.property2 = 456;
test.nest = nest;
Console.WriteLine(GenerateClass("test", (ExpandoObject)test));
}
产生:
public class test
{
String property1 { get; set; }
Int32 property2 { get; set; }
public class nest
{
String property1 { get; set; }
Int32 property2 { get; set; }
}
nest nest { get; set; }
}
好吧,这里有一些棘手的解决方案:你可以使用 JSON 序列化
using System;
using Newtonsoft.Json;
namespace XY
{
class MainClass
{
public static void Main(string[] args)
{
dynamic x = new System.Dynamic.ExpandoObject();
x.property1 = "sadsa";
var xy = JsonConvert.DeserializeObject<Test>(JsonConvert.SerializeObject(x));
Console.WriteLine(xy.property1);
Console.ReadKey();
}
}
public class Test
{
public string property1 { get; set; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.