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?
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:
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. Given your Person object, a JSON Serializer might return something like:
{"name":"Russ","Address":"1024 Oak St"}
From there, it's fairly straightforward to use Split()
and Replace()
to get close to what you want:
{ 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#.
Another way is using the T4 Text Template , such as this walkthrough . and reflection but it requires Visual Studio.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.