简体   繁体   English

生成基于填充对象的代码

[英]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. 我可以简单地将结构序列化为XML并稍后重新加载。 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 . 我会写一个T4模板 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. 我会使用json作为数据格式,并使用类似http://json2csharp.com的内容来生成用于序列化和反序列化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. 也许如果你指定为什么它绝对必须从代码生成,我们可以给出更好的答案。

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

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