Serializable class

How can I make the Student class serializable? I am reading this article, but I do not know what the right approach is if I implement it in the scenario below.

public class Student
{
    private string _studentNumber;
    private string _lastName;
    private string _firtName;
    private List<Subject> _subjects;

    public Student() { }

    public string StudentNumber
    {
        get { return _studentNumber; }
        set { _studentNumber = value; }
    }

    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    public string FirstName
    {
        get { return _firtName; }
        set { _firtName = value; }
    }

    public List<Subject> Subjects
    {
        get { return _subjects; }
        set { _subjects = value; }
    }
}

public class Subject
{
    private string _subjectCode;
    private string _subjectName;

    public Subject() { }

    public string SubjectCode
    {
        get { return _subjectCode; }
        set { _subjectCode = value; }
    }

    public string SubjectName
    {
        get { return _subjectName; }
        set { _subjectName = value; }
    }
}
+3
source share
2 answers

For BinaryFormatterjust add [Serializable]beforepublic class ....

For XmlSerializernothing; this should work fine if you want items

For DataContractSerializer(class 3.0, strictly speaking) add [DataContract]to the class and [DataMember]to the properties

protobuf-net DataContractSerializer, [DataMember] Order=, [ProtoContract] [ProtoMember(n)] , n.

JavaScriptSerializer ( 3.5) -

Json.NET -

ISerializable IXmlSerializable, , : .

+9

, IClonenable.

[Serializable()]
public class Student
{
   // Your Class
}

public static class ExtensionMethod
{  
    public static T DeepClone<T>(this T element)
    { 
        MemoryStream m = new MemoryStream();
        BinaryFormatter b = new BinaryFormatter();
        b.Serialize(m, element);
        m.Position = 0;
        return (T)b.Deserialize(m);
    }
}

yourclassobject.DeepClone();
+2

All Articles