Serializable Class

↘锁芯ラ 提交于 2019-12-12 15:01:32

问题


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

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; }
    }
}

回答1:


For BinaryFormatter, just add [Serializable] before the public class ....

For XmlSerializer, nothing; that should work fine assuming you want elements

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

For protobuf-net, you can use the DataContractSerializer attributes as long as each [DataMember] specifies a unique Order=, or you can use [ProtoContract] on the class, and [ProtoMember(n)] on each property, for unique n.

For JavaScriptSerializer (technically 3.5), nothing - it should work

For Json.NET, nothing - it should work

Other options would include implementing ISerializable or IXmlSerializable, but frankly: you don't need that.




回答2:


Usually i serialize to make a deep copy of my object without implementing IClonenable interface.

In your case you can use

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

make a extension method

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);
    }
}

and call it like

yourclassobject.DeepClone();


来源:https://stackoverflow.com/questions/10493370/serializable-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!