c#中对象序列化异常的ArrayList
本文关键字:ArrayList 异常 序列化 对象 | 更新日期: 2023-09-27 18:21:40
我有一个ArrayList,它由我创建的许多对象组成。我正在努力保留它。据我所知,最好的解决方案是使用二进制格式化程序。但是我的代码出了问题。无论是写作还是阅读,它都不起作用。这是我的密码;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private ArrayList allList = new ArrayList();
private FileStream fileStream;
private MemoryStream memoryStream;
public Form1()
{
InitializeComponent();
fileStream = new FileStream("pcdata.dat",FileMode.OpenOrCreate,FileAccess.ReadWrite);
memoryStream = new MemoryStream();
}
public void acceptDevice(Device receivedDevice)
{
//Somehow I call this method
allList.Add(receivedDevice);
saveDeviceDataToFileStream();
}
private void saveDeviceDataToFileStream()
{
SerializeToStream(allList).WriteTo(fileStream);
}
private void loadDeviceDataFromFileStream()
{
fileStream.CopyTo(memoryStream);
allList = (ArrayList)DeserializeFromStream(memoryStream);
}
public static MemoryStream SerializeToStream(object o)
{
MemoryStream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, o);
return stream;
}
public static object DeserializeFromStream(MemoryStream stream)
{
IFormatter formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
if (null == stream)
{
return null;
}
object o = formatter.Deserialize(stream);
return o;
}
}
}
这是我的设备类别:
namespace WindowsFormsApplication1
{
[Serializable]
public class Device
{
public MyPanel panel; //panel class that I created
public String id;
public int deviceNumber;
public Device(String id, int deviceNumber)
{
panel = new MyPanel();
this.id = id;
this.deviceNumber = deviceNumber;
}
}
}
这是myPanel类:
namespace WindowsFormsApplication1
{
public class MyPanel : TableLayoutPanel
{
public Panel panel1 = new Panel();
public Panel panel2 = new Panel();
public Panel panel3 = new Panel();
public Panel panel4 = new Panel();
public PictureBox pictureBox1 = new PictureBox();
public Label nameLabel = new Label();
public MyPanel()
{
//...
}
}
}
就是这样。当我尝试tun它时,我得到了一个例外:
SerializationException未处理
类型为的未处理异常中发生"System.Runtime.Serialization.Serialization异常"mscorlib.dll
附加信息:"WindowsFormsApplication1,版本=1.0.0.0,Culture=neutral,PublicKeyToken=null'Derlemesindeki"WindowsFormsApplication1.MyPanel"…
我不认为您能够仅仅序列化这样的控件。我建议围绕要保存的数据创建类,并使控件只负责显示。
[Serializable]
public class MyPanelInfo
{
public PanelInfo panel1;
public PanelInfo panel2;
public PanelInfo panel3;
public PanelInfo panel4;
public Image image;
public string nameLabel;
public MyPanelInfo()
{
}
}
[Serializable]
public class PanelInfo
{
public string id;
public string name;
}