【问题标题】:Understanding Serialization了解序列化
【发布时间】:2015-06-16 00:09:03
【问题描述】:

上下文

我正在尝试了解如何使用序列化,以前从未使用过。

现在我在我的单例对象(主类)中有一个填充方法,它基本上使用我的 addMember 方法将一些成员对象添加到成员列表中

我想序列化这个成员列表一旦我可以序列化和反序列化列表,我就可以删除我的填充方法。

问题

  • 如何序列化此列表,以便在启动时反序列化成员列表?

  • 我在哪里专门序列化?我是在创建新成员时进行序列化,还是在关闭时序列化列表并在启动时反序列化。

  • 既然会员信息可以编辑,那如何序列化更新,覆盖之前持有的数据?

代码清单

我对序列化有点陌生,但这是我的代码,我为此使用了一种方法,因为我认为这种方式更干净,在我的主类中使用 ISerializable。这是我的主要课程中的一些 sn-ps,请记住,我的代码中有大量 cmets,这就是我之前没有发布此内容的原因:

namespace HillRacingGraded
{
    [Serializable]
    public class HillRacing : ISerializable
    {
        /// <summary>
        /// Singleton object hillracing
        /// </summary>
        private static HillRacing hillracing;

        GUIUtility gui = new GUIUtility();


        /// <summary>
        /// Instance property returns the singleton instance
        /// </summary>
        public static HillRacing Instance
        {
            get
            {
                if (hillracing == null)
                    hillracing = new HillRacing();
                return hillracing;
            }
        }

        /// <summary>
        /// public Property that returns races list, can be accessed by other classes.
        /// </summary>
        public List<BaseRace> Races
        {
            get
            {
                return races;
            }
            set
            {
                races = value;
            }
        }
        /// <summary>
        /// public Property that returns members list, can be accessed by other classes.
        /// </summary>
        public List<BaseMember> Members
        {
            get
            {
                return members;
            }
            set
            {
                members = value;
            }
        }

        /// <summary>
        /// instantiate the list of members
        /// </summary>
        private List<BaseMember> members; //I WANT TO SERIALIZE THIS

        /// <summary>
        /// instantiate the list of races
        /// </summary>
        private List<BaseRace> races; //I WANT TO SERIALIZE THIS

        /// <summary>
        /// Default constructor for hillracing.
        /// </summary>
        public HillRacing()
        {
            //members is a new list of the BaseMember objects.
            //races is a new list of the BaseRace objects.


            members = new List<BaseMember>();
            races = new List<BaseRace>();

            //call the populate method on launch, mostly for testing purposes.
            Populate();


        }

        /// <summary>
        /// Hillracing constructor for serialization
        /// </summary>
        /// <param name="info"></param>
        /// <param name="ctxt"></param>
        public HillRacing(SerializationInfo info, StreamingContext ctxt)
        {
             this.members = (List<BaseMember>)info.GetValue("Members", typeof(List<BaseMember>));
             this.races = (List<BaseRace>)info.GetValue("Races", typeof(List<BaseRace>));
        }

        /// <summary>
        /// get object data
        /// </summary>
        /// <param name="info"></param>
        /// <param name="ctxt"></param>
        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
         {
             info.AddValue("Members", this.members);
         }


        /// <summary>
        ///  Adds a new junior member to the list of all members.
        /// </summary>
        /// <param name="stringfirstname">first name of the member</param>
        /// <param name="stringlastname">last name of the member</param>
        /// <param name="stringmiddlename">middle name of the member</param>
        /// <param name="stringtitle">title of the member</param>
        /// <param name="strst">street of the member</param>
        /// <param name="strtwn">Town of the member</param>
        /// <param name="strpc">Postcode of the member</param>
        /// <param name="strEmail">email of the member</param>
        /// <param name="intMobile">Mobile of the member</param>
        /// <param name="intHome">Home phone of the member</param>
        /// <param name="shrnumber">ID number of the member</param>
        /// <param name="memtype">Type of the member</param>
        /// <param name="username">username of the member</param>
        /// <param name="noracesrun">number of races that the member has run</param>
        /// <param name="perraceswon">percentage of races that the member has won</param>
        /// <param name="mempic">image of the member</param>
        /// <param name="memclub">the club the member is part of</param>
        /// <param name="gender">the gender of the member</param>
        /// <param name="memexp">the experience level the member has</param>
        /// <param name="yearofbirth">the year of birth the member was born in</param>
        /// <param name="monthofbirth">the month of birth the member was born in</param>
        /// <param name="dayofbirth">the day of birth the member was born on</param>
        public void addJunior(string stringfirstname, string stringlastname, string stringmiddlename, string stringtitle, string strst, string strtwn, string strpc, string strEmail, int intMobile, int intHome,
            string shrnumber, string memtype, string username, string password, int noracesrun, float perraceswon, string mempic, string memclub, string gender, int memexp, int yearofbirth, int monthofbirth, int dayofbirth, string nextofkin, string docName, string docTel, string healthIssues, string parentalConsent)
        {

            // create a new member with the entered parameters to add to the list.
            JuniorMember newMember = new JuniorMember(stringfirstname, stringlastname, stringmiddlename, stringtitle, strst, strtwn, strpc, strEmail, intMobile, intHome, shrnumber, memtype, username, password, noracesrun, perraceswon, mempic, memclub, gender, memexp, yearofbirth, monthofbirth, dayofbirth,nextofkin,docName,docTel,healthIssues,parentalConsent);

            //use add functionality of list to add to the list.
            members.Add(newMember);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="stringfirstname">first name of the member</param>
        /// <param name="stringlastname">last name of the member</param>
        /// <param name="stringmiddlename">middle name of the member</param>
        /// <param name="stringtitle">title of the member</param>
        /// <param name="strst">street of the member</param>
        /// <param name="strtwn">Town of the member</param>
        /// <param name="strpc">Postcode of the member</param>
        /// <param name="strEmail">email of the member</param>
        /// <param name="intMobile">Mobile of the member</param>
        /// <param name="intHome">Home phone of the member</param>
        /// <param name="shrnumber">ID number of the member</param>
        /// <param name="memtype">Type of the member</param>
        /// <param name="username">username of the member</param>
        /// <param name="noracesrun">number of races that the member has run</param>
        /// <param name="perraceswon">percentage of races that the member has won</param>
        /// <param name="mempic">image of the member</param>
        /// <param name="memclub">the club the member is part of</param>
        /// <param name="gender">the gender of the member</param>
        /// <param name="memexp">the experience level the member has</param>
        /// <param name="yearofbirth">the year of birth the member was born in</param>
        /// <param name="monthofbirth">the month of birth the member was born in</param>
        /// <param name="dayofbirth">the day of birth the member was born on</param>
        /// <param name="nextofkin">The next family member contact</param>
        /// <param name="docName">The name of the members doctor</param>
        /// <param name="docTel">A telephone number for the doctor</param>
        /// <param name="healthIssues">the health issues this member has.</param>
        public void addSenior(string stringfirstname, string stringlastname, string stringmiddlename, string stringtitle, string strst, string strtwn, string strpc, string strEmail, int intMobile, int intHome,
            string shrnumber, string memtype, string username, string password, int noracesrun, float perraceswon, string mempic, string memclub, string gender, int memexp, int yearofbirth, int monthofbirth, int dayofbirth, string nextofkin, string docName, string docTel, string healthIssues)
        {

            //create a new member with the entered parameters to add to the list.
            SeniorMember newMember = new SeniorMember(stringfirstname, stringlastname, stringmiddlename, stringtitle, strst, strtwn, strpc, strEmail, intMobile, intHome, shrnumber, memtype, username, password, noracesrun, perraceswon, mempic, memclub, gender, memexp, yearofbirth, monthofbirth, dayofbirth,docName,docTel,healthIssues);

            //use standard list functionality of list to add this new member to the list.
            members.Add(newMember);

        }

这是我在 Serializer 类中的序列化方法:

    public void SerializeObject(string filename, object objectToSerialize)
    {
        Stream stream = File.Open(filename + ".bin", FileMode.Create);
        BinaryFormatter bFormatter = new BinaryFormatter();
        bFormatter.Serialize(stream, objectToSerialize);
        stream.Close();
    }

问题是,我不知道如何实际使用它。

还有一个反序列化器:

public HillRacing DeSerializeObject(string filename)
{
    HillRacing hillracing;
    Stream stream = File.Open(filename + ".bin", FileMode.Open);
    BinaryFormatter bFormatter = new BinaryFormatter();
    hillracing = (HillRacing)bFormatter.Deserialize(stream);
    stream.Close();
    return hillracing;
}

【问题讨论】:

  • “我对序列化有点陌生。” - 所以大概搜索某种介绍性教程可能会有用....
  • 他们非常复杂,我正在寻找一个简单的解释性回应。
  • 所以,你是说那里的每个教程都无法理解?
  • “我创建了一个 Serializer 类,并试图让它与我的代码一起工作” -- 大概它不起作用?请提供a good, minimal, complete code example,清楚地显示您尝试过的内容,并清楚、准确地描述该代码的作用以及它与您想要它做的不同之处。如前所述,您的问题对于 Stack Overflow 来说太宽泛了。通过提供具体的详细信息来帮助他人帮助您,以帮助您了解如何让代码正常工作。

标签: c# serialization


【解决方案1】:

虽然你已经完成了大部分工作,但我建议使用一些泛型使其多用途

public static class StreamUtilities
{
    public static T GetObject<T>(Byte[] rawimage) where T : class
    {
        try
        {
            MemoryStream memStream = new MemoryStream();

            BinaryFormatter binForm = new BinaryFormatter();
            memStream.Write(rawimage, 0, rawimage.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            return binForm.Deserialize(memStream) as T;
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    public static  Byte[] Serialize<T>(this T obj) where T:class
    {
        if (obj == null)
            return null;
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

然后在您的主类或您希望它使用的任何地方包含到命名空间,然后使用上述扩展方法

Object1 a=new Object1();// any serializable object
serializedbytes=a.Serialize<Object1>();
//deserialize
Object b=StreamUtilities.GetObject<Object1>(serializedbytes);

上述扩展方法将允许序列化/反序列化任何可序列化的对象。

【讨论】:

    猜你喜欢
    • 2015-02-22
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 2017-03-08
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多