Serializing/deserializing with memory stream

前端 未结 3 1547
难免孤独
难免孤独 2020-11-30 01:27

I\'m having an issue with serializing using memory stream. Here is my code:

/// 
/// serializes the given object into memory stream
///          


        
3条回答
  •  天涯浪人
    2020-11-30 01:52

    This code works for me:

    public void Run()
    {
        Dog myDog = new Dog();
        myDog.Name= "Foo";
        myDog.Color = DogColor.Brown;
    
        System.Console.WriteLine("{0}", myDog.ToString());
    
        MemoryStream stream = SerializeToStream(myDog);
    
        Dog newDog = (Dog)DeserializeFromStream(stream);
    
        System.Console.WriteLine("{0}", newDog.ToString());
    }
    

    Where the types are like this:

    [Serializable]
    public enum DogColor
    {
        Brown,
        Black,
        Mottled
    }
    
    [Serializable]
    public class Dog
    {
        public String Name
        {
            get; set;
        }
    
        public DogColor Color
        {
            get;set;
        }
    
        public override String ToString()
        {
            return String.Format("Dog: {0}/{1}", Name, Color);
        }
    }
    

    and the utility methods are:

    public static MemoryStream SerializeToStream(object o)
    {
        MemoryStream stream = new MemoryStream();
        IFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, o);
        return stream;
    }
    
    public static object DeserializeFromStream(MemoryStream stream)
    {
        IFormatter formatter = new BinaryFormatter();
        stream.Seek(0, SeekOrigin.Begin);
        object o = formatter.Deserialize(stream);
        return o;
    }
    

提交回复
热议问题