5

我在 c# 中有不同类型的对象,我想将它们保存到文件中(首选 XML),但我不能使用序列化,因为该类不是我编写的,而是来自 DLL。

什么是最好的解决方案?

4

5 回答 5

3

我最终使用了 JavaScriptSerializer,它完全符合我的要求:

List<Person> persons = new List<Person>();
persons.Add(new Person(){Name = "aaa"});
persons.Add(new Person() { Name = "bbb" });

JavaScriptSerializer javaScriptSerializer  = new JavaScriptSerializer();
var strData = javaScriptSerializer.Serialize(persons);

var persons2 = javaScriptSerializer.Deserialize<List<Person>>(strData);
于 2013-02-02T01:03:55.970 回答
1

给定一个不可序列化的对象,我创建了一个快速的小扩展方法,它将“序列化”为 XML。它非常粗糙,不会进行大量检查,并且它生成的 XML 可以轻松调整以满足您的需求:

public static string SerializeObject<T>(this T source, bool serializeNonPublic = false)
{
    if (source == null)
    {
        return null;
    }

    var bindingFlags = BindingFlags.Instance | BindingFlags.Public;

    if (serializeNonPublic)
    {
        bindingFlags |= BindingFlags.NonPublic;
    }

    var properties = typeof(T).GetProperties(bindingFlags).Where(property => property.CanRead).ToList();
    var sb = new StringBuilder();

    using (var writer = XmlWriter.Create(sb))
    {
        writer.WriteStartElement(typeof(T).Name);
        if (properties.Any())
        {
            foreach (var property in properties)
            {
                var value = property.GetValue(source, null);

                writer.WriteStartElement(property.Name);
                writer.WriteAttributeString("Type", property.PropertyType.Name);
                writer.WriteAttributeString("Value", value.ToString());
                writer.WriteEndElement();
            }
        }
        else if (typeof(T).IsValueType)
        {
            writer.WriteValue(source.ToString());
        }

        writer.WriteEndElement();
    }

    return sb.ToString();
}

我在这堂课上测试了它:

private sealed class Test
{
    private readonly string name;

    private readonly int age;

    public Test(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public string Name
    {
        get
        {
            return this.name;
        }
    }

    public int Age
    {
        get
        {
            return this.age;
        }
    }
}

以及数字3object。生成的 XML 如下所示:

<?xml version="1.0" encoding="utf-16"?>
<Test>
  <Name Type="String" Value="John Doe" />
  <Age Type="Int32" Value="35" />
</Test>

<?xml version="1.0" encoding="utf-16"?>
<Int32>3</Int32>

<?xml version="1.0" encoding="utf-16"?>
<Object />

分别。

于 2013-01-31T16:05:57.553 回答
0

围绕 DLL 的不可序列化类编写自己的可序列化包装器。

编辑:评论中建议使用 AutoMapper,但我还没有听说过,但现在我肯定会使用它而不是自己编写包装器。除非需要一些反射来捕获不可序列化对象的某些内部状态(如果可能),否则我不知道 AutoMapper 是否可以提供任何东西,或者您必须查看是否可以在包装器中捕获它.

于 2013-01-31T15:13:01.380 回答
0

我认为问题标题中的“无序列化”一词具有误导性。

如果我理解正确,您想要序列化没有序列化属性的对象。

有诸如sharpserializerprotobuf-net之类的库可以为您完成这项工作。

于 2013-01-31T16:05:55.163 回答
0

我会编写一个 POCO(普通旧类对象)类来模仿返回的 DLL 中的对象。通常,如果您使用的是 .NET 3.5 或更高版本,您就可以使用 LINQ。我赞成 Linq 将对象放入其他类或对它们执行排序或其他操作。

这是一个简单的示例,例如,您将在返回对象中进行模拟。请记住,在 DLL 中,您当然可以拥有许多不同的对象并多次执行此操作。我也会将我的方法封装在他们自己的类中以实现重用,而不是在主类中进行。但这是一个简单的概念证明

using System;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Xml.Linq;

namespace ExampleSerializer
{
    class Program
    {
        // example class to serialize
        [Serializable]
        public class SQLBit
        {
            [XmlElement("Name")]
            public string Name { get; set; }

            [XmlText]
            public string data { get; set; }
        }

        // example class to populate to get test data
        public class example
        {
            public string Name { get; set; }
            public string data { get; set; }
        }

        static void Main(string[] args)
        {
            string s = "";

            // make a generic and put some data in it from the test
            var ls = new List<example> { new example { Name = "thing", data = "data" }, new example { Name = "thing2", data = "data2" } };

            // make a second generic and put data from the first one in using a lambda
            // statement creation method.  If your object returned from DLL is a of a
            // type that implements IEnumerable it should be able to be used.
            var otherlist = ls.Select(n => new SQLBit
                {
                    Name = n.Name,
                    data = n.data
                });

            // start a new xml serialization with a type.
            XmlSerializer xmler = new XmlSerializer(typeof(List<SQLBit>));

            // I use a textwriter to start a new instance of a stream writer
            TextWriter twrtr = new StreamWriter(@"C:\Test\Filename.xml");

            // Serialize the stream to the location with the list
            xmler.Serialize(twrtr, otherlist);

            // Close
            twrtr.Close();

            // TODO: You may want to put this in a try catch wrapper and make up your 
            // own classes.  This is a simple example.
         }
    }
}
于 2013-01-31T15:46:35.520 回答