简体   繁体   English

我将如何获得等效的C#代码,以其当前状态重新创建运行时对象?

[英]How would I get the equivalent C# code that will recreate my runtime object in its current state?

Are there any .Net libraries which can take an object and serialize it to a Stream, as the C# code that would create the object? 是否有任何.Net库可以接受对象并将其序列化为Stream,就像创建对象的C#代码一样?

Stream fs = ...;

CSharpFormatter formatter = new CSharpFormatter();

var p = new Person { Name = "Russ", Address = "1024 Oak St" };

formatter.Serialize(fs, p);

At the end of this, fs would end up with a string like this written to it: 在此结束时,fs将以这样的字符串结尾:

new Person { Name = "Russ", Address = "1024 Oak St" };

I think something like this would be very useful in writing unit tests from tricky runtime cases. 我认为类似这样的事情对于在棘手的运行时案例中编写单元测试非常有用。

You could potentially hack a JSON serializer to do this. 您可能会破解JSON序列化程序来执行此操作。 Given your Person object, a JSON Serializer might return something like: 给定您的Person对象,JSON序列化器可能返回以下内容:

{"name":"Russ","Address":"1024 Oak St"}

From there, it's fairly straightforward to use Split() and Replace() to get close to what you want: 从那里开始,使用Split()Replace()可以很轻松地接近所需的内容:

{ Name = "Russ", Address = "1024 Oak St" }

The rest is just window dressing. 剩下的只是窗帘。

Only a partial answer but you can use classes in the System.CodeDom namespace to create the code, such as this example , then use GenerateCodeFromXXX methods in the CSharpCodeProvider class to emit C#. 只有部分答案,但是您可以使用System.CodeDom命名空间中的类来创建代码(如本示例) ,然后使用CSharpCodeProvider类中的GenerateCodeFromXXX方法发出C#。

Another way is using the T4 Text Template , such as this walkthrough . 另一种方法是使用T4文本模板 ,例如本演练 and reflection but it requires Visual Studio. 和反射,但它需要Visual Studio。

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

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