首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

问个序列化有关问题

2011-12-22 
问个序列化问题[Serializable]classA{privateString_pathpublicA(){}}[Serializable]classB:ObservableCo

问个序列化问题
[Serializable]
class   A
{
private   String   _path;
public   A()   {}
}

[Serializable]
class   B:   ObservableCollection <A> ,ISerializable  
{
public   B(){}

#region   ISerializable   成员
public   void   GetObjectData(SerializationInfo   info,   StreamingContext   context)
                {
                        //???????????????????这里该怎么写?????????????????
                }
#endregion
}

class   C
{
private   String   _strFile;
private   B   _items   =   new   B();;
public   C(){}

public   void   FromFile
{
.............
}

public   void   ToFile
{
try
{
        using   (FileStream   fs   =   new   FileStream(_strFile,   FileMode.Create))
        {
                BinaryFormatter   formatter   =   new   BinaryFormatter();
                formatter.Serialize(fs,   _items);
        }
}
catch   (SerializationException   e)
{
}
}

ObservableCollection <T> 内部有些成员不能被序列化,   所以才使用了ISerializable,
问题是B.GetObjectData(...)该怎么写,   才能将C._items顺利序列化和反序列化?

[解决办法]
===========================
//静态方法Serialize,将一个对象序列化为一个文件
public static void Serialize(object data, string filePath)
{ try
{
//打开文件
StreamWriter fs = new StreamWriter(filePath, false);
try
{
// 创建其支持存储区为内存的流
MemoryStream streamMemory = new MemoryStream();
// 以二进制格式将对象或整个连接对象图形序列化或反序列化
BinaryFormatter formater = new BinaryFormatter();
//将这个对象序列化到内存流中
formater.Serialize(streamMemory, data);
//先转换为字符串的形式
string binaryData = Convert.ToBase64String(streamMemory.GetBuffer());

//将数据 写入到文件
fs.Write(binaryData);
}
catch (Exception ex)
{
throw ex;
}
finally
{
fs.Flush();
fs.Close();
}
}
catch(Exception ex)
{
throw ex;
}

热点排行