日期:2014-05-20  浏览次数:20776 次

怎样序列化一个类对象到数据库中,没想法,请高手提点!
。。

------解决方案--------------------
//将一个对象序列化成二进制数组
private byte[] SerializeToByte(ArrayList list)
{
//假如Arraylist为空,则返回null
if (list.Count == 0)
{
return null;
}
byte[] array = null;
try
{
//定义一个流
Stream stream = new MemoryStream();
//定义一个格式化器
BinaryFormatter bf = new BinaryFormatter();
//将Arraylist中的对象逐一进行序列化
foreach (object obj in list)
{
bf.Serialize(stream, obj);
}
array = new byte[stream.Length];
//将二进制流写入数组
stream.Position = 0;
stream.Read(array, 0, (int)stream.Length);
//关闭流
stream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
return array;
}

//将一个二进制数组反序列化
private ArrayList DeseralizeToArraylist(byte[] b)
{
if (b == null || b.Length == 0)
{
return null;
}
//定义一个流
MemoryStream stream = new MemoryStream(b);
//定义一个格式化器
BinaryFormatter bf = new BinaryFormatter();
ArrayList list = new ArrayList();
while (stream.Position != stream.Length)
{
list.Add(bf.Deserialize(stream));
}
stream.Close();
return list;
}

------解决方案--------------------
先序列化为一string或其他,再存string或其他到数据库。
------解决方案--------------------
先序列化成二进制数组,然后再插入数据库,插入数据库我就不多说了...

取出也一样,先得到二进制数组,然后再反序列化...

有关序列化更多请参见:

http://community.csdn.net/Expert/topic/5298/5298838.xml?temp=.3514826
------解决方案--------------------
以2进制的形式来序列化那个对象,然后在存储到数据库中,不就可以了嘛。