How to Serialize List?

后端 未结 7 697
长发绾君心
长发绾君心 2020-11-30 11:05

I have Class A. Class B and Class C are part of Class A.

Class A 
{

//Few Properties of Class A

List list1 = new List()

         


        
7条回答
  •  一整个雨季
    2020-11-30 12:05

    Easiest way: to do BINARY serialization of any object (Images also and lot of other data!) with IO error catching.

    To the class that we need to serialize we need to add [Serializable]

    [Serializable]//this like
    public class SomeItem
    {}
    

    Serialization wrapper:

    public static class Serializator
    {
        private static BinaryFormatter _bin = new BinaryFormatter();
    
        public static void Serialize(string pathOrFileName, object objToSerialise)
        {
            using (Stream stream = File.Open(pathOrFileName, FileMode.Create))
            {
                try 
                {
                    _bin.Serialize(stream, objToSerialise);
                }
                catch (SerializationException e) 
                {
                    Console.WriteLine("Failed to serialize. Reason: " + e.Message);
                    throw;
                }
            }
        }
    
        public static T Deserialize(string pathOrFileName) 
        {
            T items;
    
            using (Stream stream = File.Open(pathOrFileName, FileMode.Open))
            {
                try 
                {
                    items = (T) _bin.Deserialize(stream);
                }
                catch (SerializationException e) 
                {
                    Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
                    throw;
                }
            }
    
            return items;
        }
    }
    

    and using of the solution:

    List itemsCollected; //list with some data
    
    Serializator.Serialize("data.dat", itemsCollected); // trying to serialise
    
    
    var a = Serializator.Deserialize<%dataType%>("%dataPath%");
    
    var a = Serializator.Deserialize>("data.dat");
    // trying to DeSerialize; 
    // And important thing that you need to write here 
    // correct data format instead of List
    

    in case of error was occured, error will be written to the console.

提交回复
热议问题