简体   繁体   中英

Generate code based which populate an object

Let's 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's somecode that instanciate that class and populates it with all the data. I'd like to use that object for my test. I could simply serialize the structure into XML and reload it later. However, what I would really like is to have the entire object tree build in the code. In other words:

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

I could write all that myself, but it would take hours and be error prone since there's a high number of properties and sub-classes. Here's my question: given an object how would you generate the code which populate that object?

I would write a T4 template . Check out an example that is doing something, although really remotely, similar to what you need.

I would use json for a data format and use something like http://json2csharp.com to generate classes to use to serialize and deserialize to and from json. Or given the classes already existing annotate them and serialize them out.

This will handle any arbitrary nesting and be maintainable. Values can even be edited without a recompile which is usually a good thing. The link also leads to examples for how to specify specific types, handle enums, object links, etc.

Perhaps if you specify why it absolutely has to be generated from code only we can give better answers.

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.

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