简体   繁体   English

在C#中序列化嵌套对象

[英]Serialize nested objects in C#

I got 2 user-defined classes, called Event and Image , Event has a property stored a list of EventImage , called EventImages . 我有2个用户定义的类,分别称为EventImageEvent具有一个存储了EventImage列表的属性 ,该列表称为EventImages And in Image class, there's a byte[] type property which store the byte[] of one Image file. Image类中,有一个byte []类型属性,用于存储一个Image文件的byte []。

Here's the definitions of the 2 classes : 这是2个类的定义:

[Serializable]
public Class Event
{
    public String Name {get; set;}
    public DateTime EventTime { get; set;}
    public List<Image> EventImages { get; set; }
    ...
}

[Serializable]
public Class Image
{
    public DateTime ImageTime { get; set;}
    public byte[] pData {get; set;}
    ...
}

Now my question is, I want to serialize my Event object to byte[] , and I expect that the whole content of it will be serialize , too, but it seems that I failed. 现在我的问题是,我想将Event对象序列化为byte [] ,并且我希望它的全部内容也可以序列化 ,但是看来我失败了。

Here's my code to do Serialization : 这是我执行序列化的代码:

    public static byte[] ObjectToByteArray(object obj)
    {
        if (obj == null)
        {
            return null;
        }
        else
        {
            BinaryFormatter bF = new BinaryFormatter();
            using (MemoryStream mS = new MemoryStream())
            {
                bF.Serialize(mS, obj);
                return mS.ToArray();
            }
        }
    }

and here's the code for verification : 这是验证代码:

Console.WriteLine(ObjectToByteArray(Event));
Console.WriteLine(ObjectToByteArray(Event.EventImage));        
Console.WriteLine(ObjectToByteArray(Event.EventImages.FirstOrDefault().pData));

and the results are(just assumption value) : 100 200 300 结果是(只是假设值):100200300

But I expect the result should be 600(100+200+300), 500(200+300) and 300. 但我希望结果应该是600(100 + 200 + 300),500(200 + 300)和300。

So, I think my serialization doesn't really serialize the whole content, it just serialize properties with Basic Types, but without the nested objects, am I right? 所以,我认为我的序列化并没有真正序列化整个内容,它只是序列化了具有Basic Types的属性,但是没有嵌套的对象,对吗?

I've searched lots of posts, and I found plenty of answers to similar questions mentioned "XML Serialization", but I'm not sure whether its helpful or not. 我搜索了很多帖子,找到了许多类似“ XML序列化”的类似问题的答案,但是我不确定它是否有用。 Need I use that or is there any other better way? 我需要使用它还是有其他更好的方法? Thanks in advance! 提前致谢!

Quickly made a test to check equality. 快速进行测试以检查是否相等。 It passes. 它通过了。

Serializes and deserializes correctly. 正确地序列化和反序列化。

Conclusion, don't judge whether something is happening or not until you've tested it. 结论,在测试之前不要判断是否正在发生任何事情。

    public static void Run()
    {
        var i = new Image
        {
            ImageTime = DateTime.UtcNow,
            pData = Guid.NewGuid().ToByteArray()
        };

        var e = new Event
        {
            Name = Guid.NewGuid().ToString(),
            EventTime = DateTime.UtcNow,
            EventImages = new List<Image> {i}
        };

        var bytes = ObjectToByteArray(e);
        var e2 = ObjectFromByteArray(bytes);

        Console.WriteLine(e.Equals(e2));
    }

    public static byte[] ObjectToByteArray(object obj)
    {
        if (obj == null)
        {
            return null;
        }

        var bF = new BinaryFormatter();
        using (var mS = new MemoryStream())
        {
            bF.Serialize(mS, obj);
            return mS.ToArray();
        }
    }

    public static object ObjectFromByteArray(byte[] bytes)
    {
        if (bytes == null)
        {
            return null;
        }

        var bF = new BinaryFormatter();
        using (var mS = new MemoryStream(bytes))
        {
            return bF.Deserialize(mS);
        }
    }

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

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