本文介绍了可序列化的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使学生类可序列化?我正在阅读此,但我不知道如果我使用哪种正确的方法

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


推荐答案

对于 BinaryFormatter ,只需在公共类之前添加 [可序列化] 。 code>

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

对于 XmlSerializer ,什么都没有;假设您想要元素,该方法应该可以正常工作

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

对于 DataContractSerializer (严格来说是3.0类),添加 [DataContract] 到该类, [DataMember] 到属性

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

对于protobuf-net,只要每个 [DataMember] 指定一个唯一值,就可以使用 DataContractSerializer 属性 Order = ,或者您可以在该类上使用 [ProtoContract] [ProtoMember( n)] ,对于每个 n

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.

对于 JavaScriptSerializer (技术上为3.5),什么都没有-应该可以工作

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

对于 Json.NET ,什么也没有-它应该可以工作

For Json.NET, nothing - it should work

其他选择包括实现 ISerializable IXmlSerializable ,但坦率地说:您不需要。

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

这篇关于可序列化的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 05:46