Can you please explain why the following piece of code fails to work?

static void Main(string[] args)
    {
        var simpleObject = new SimpleObjectDTO { Id = 1, Name = "Jacob" };
        const string format = "{2} object properties are: Id {0} Name {1}";
        Console.WriteLine(format, simpleObject.Id, simpleObject.Name, "Original");
        var clone = simpleObject.Clone() as SimpleObjectDTO;
        // ReSharper disable PossibleNullReferenceException
        Console.WriteLine(format, clone.Id, clone.Name, "Clone");
        // ReSharper restore PossibleNullReferenceException
        Console.ReadLine();
    }

where

[ProtoContract]
public class SimpleObjectDTO  : ICloneable
{
    [ProtoMember(1)]
    public int Id { get; set; }
    [ProtoMember(2)]
    public string Name { get; set; }

    public object Clone()
    {
        using (var stream = new MemoryStream())
        {
            Serializer.Serialize(stream, this);
            stream.Flush();
            var clone = Serializer.Deserialize<SimpleObjectDTO>(stream);
            return clone;
        }            
    }
}

The code runs just fine but the deserialized object has 0 and an empty string as the appropriate properties' values.

Upd.: If I serialize into a binary file and then open if for reading thus creating a new stream the code works. Is there any possibility of avoiding intermediate binary files and using only one stream for both serializing and deserializing?

有帮助吗?

解决方案

Thr problem is the stream's position needs to be reset to zero.

As an alternative:

return Serializer.DeepClone(this);

其他提示

Figured out the issue, forgot to reset the memory stream's position

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top