通过重写基类的Write()和Read()方法将数据写入文件?

时间:2012-09-15 15:09:50

标签: c# serialization persistence deserialization grasshopper

我正在尝试将数据写入文件,下面的代码包含writer方法,该方法允许覆盖基类write()的{​​{1}}方法。代码编译时没有错误,但数据没有按计划编写。我做错了什么?

GH_Component

1 个答案:

答案 0 :(得分:1)

我需要覆盖GH_Component上的Write()和Read()方法:

 //deserializes the variable m_settings to make the data persistant
        public override bool Write(GH_IWriter writer)
        {
            if (m_settings != null && m_settings.Length > 0)
            {
                writer.SetInt32("StringCount", m_settings.Length);
                for (int i = 0; i < m_settings.Length; i++)
                {
                    writer.SetString("String", i, m_settings[i]);
                }
            }

            return base.Write(writer);
        }

        //deserializes the variable m_settings to make the data persistant
        public override bool Read(GH_IReader reader)
        {
            m_settings = null;

            int count = 0;
            reader.TryGetInt32("StringCount", ref count);
            if (count > 0)
            {
                System.Array.Resize(ref m_settings, count);
                for (int i = 0; i < count; i++)
                {
                    string line = null;
                    reader.TryGetString("String", i, ref line);
                    m_settings[i] = line;
                }
            }

            return base.Read(reader);
        }