我怎样才能将对象序列化到C#对象初始化代码? [英] How can I serialize an object to C# object initializer code?

查看:123
本文介绍了我怎样才能将对象序列化到C#对象初始化代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望利用内存中的对象(或JSON序列化对象)和生成C#代码生成一个对应的对象。

I'm looking to take an in-memory object (or JSON serialization of an object) and emit C# code to produce an equivalent object.

这是拉从库中已知很好的例子在单元测试中使用为出发点非常有用。我们认为反序列化JSON,但是当涉及到​​重构的C#代码将有一个优势。

This would be useful for pulling known-good examples from a repository to use as starting points in unit tests. We have considered deserializing JSON, but C# code would have an edge when it comes to refactoring.

推荐答案

如果你的模式很简单,你可以使用反射和一​​个字符串生成器输出C#直接。我做这个来填充单元测试数据完全像你讨论。

If your model is simple, you could use reflection and a string builder to output C# directly. I've done this to populate unit test data exactly like you discussed.

下面的代码样本写在了几分钟,并生成需要一些调整手的对象初始化。如果你打算做这个有很多更健壮/ bug更少的功能可以写。

The code sample below was written in a few minutes, and generated an object initializer that needed some hand tweaking. A more robust / less buggy function could be written if you plan on doing this a lot.

的第二个功能是递归的,在对象内遍历任何解释,并为那些产生代码。

The second function is recursive, iterating over any Lists within the object and generating code for those as well.

免责声明:这个工作对我的基本数据类型的简单模型。它产生的,需要清理的代码,但让我快速前进。这是只有在这里充当的是如何可以这样做的例子。希望它激发人写自己的。

Disclaimer: This worked for my simple model with basic datatypes. It generated code that needed cleanup, but allowed me to move on quickly. It is only here to serve as an example of how this could be done. Hopefully it inspires someone to write their own.

在我的情况,我有这个大的数据集(结果),这是从数据库加载的实例。为了消除来自我的单元测试数据库的依赖,我递给对象这个功能,吐了出来,让我嘲笑的对象在我的测试类的代码。

In my case, I had an instance of this large dataset (results) that was loaded from the database. In order to remove the database dependency from my unit test, I handed the object to this function which spit out the code that allowed me to mock the object in my test class.

    private void WriteInstanciationCodeFromObject(IList results)
    {

        //declare the object that will eventually house C# initialization code for this class
        var testMockObject = new System.Text.StringBuilder();

        //start building code for this object
        ConstructAndFillProperties(testMockObject, results);

        var codeOutput = testMockObject.ToString();
    }


    private void ConstructAndFillProperties(StringBuilder testMockObject, IList results)
    {

        testMockObject.AppendLine("var testMock = new " + results.GetType().ToString() + "();");

        foreach (object obj in results)
        {

            //if this object is a list, write code for it's contents

            if (obj.GetType().GetInterfaces().Contains(typeof(IList)))
            {
                ConstructAndFillProperties(testMockObject, (IList)obj);
            }

            testMockObject.AppendLine("testMock.Add(new " + obj.GetType().Name + "() {");

            foreach (var property in obj.GetType().GetProperties())
            {

               //if this property is a list, write code for it's contents
                if (property.PropertyType.GetInterfaces().Contains(typeof(IList)))
                {
                    ConstructAndFillProperties(testMockObject, (IList)property.GetValue(obj, null));
                }

                testMockObject.AppendLine(property.Name + " = (" + property.PropertyType + ")\"" + property.GetValue(obj, null) + "\",");
            }

            testMockObject.AppendLine("});");
        }
    }

这篇关于我怎样才能将对象序列化到C#对象初始化代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆