Create code based on which the object is populated

Say I have the following classes.

public class MyClass { public string Data1 { get; set; } public MyOtherClass Data2 { get; set; } // 50+ other properties... } public class MyOtherClass { public string OtherData1 { get; set; } // More properties } 

There is somecode that initializes this class and fills it with all the data. I would like to use this object for my test. I could just serialize the structure to XML and reload it later. However, I would like the entire tree of objects to be built in the code. In other words:

 MyClass myClass = new MyClass { Data1 = "Hello", Data2 = new MyOtherClass { OtherData1 = "World", // More... }, // More... } 

I could write all this myself, but it will take several hours and be error prone since there are a large number of properties and subclasses. Here's my question: an object is asked, how would you generate code that populates this object?

+6
source share
2 answers

I would write a T4 template. Check out an example that does something, although really remotely, it sounds like what you need.

+1
source

I would use json for the data format and use something like http://json2csharp.com to create classes that will be used for serialization and deserialization in json and from json, Or if existing classes annotate them and serialize them.

This will handle any arbitrary nested and supported. The values ​​can even be edited without recompilation, which is usually good. A link also gives examples of how to specify specific types, describe enumerations, object references, etc.

Perhaps if you indicate why it is absolutely necessary to generate from the code, we can give better answers.

0
source

Source: https://habr.com/ru/post/920900/


All Articles