在应用会话之间持久存储集合

本文介绍如何通过序列化和反序列化方法保存和恢复应用程序状态,包括使用BinaryFormatter进行对象序列化到文件和从文件反序列化对象的具体实现。
一个集合,如ArrayList,List<T>,Hashtable,或Dictionary<T,U>,其中存储着应用信息。可以使用这些信息将应用环境调整为上一个已知的设置(如:窗口大小,窗口摆放,当前显示的工具条等等,)还可以用它来允许用户从其最后一次关闭处启动应用。也就是说,如果用户在编辑一个发货单,因为太晚了而需要关闭计算机,应用它能准确地知道下一次启动应用时要显示哪个发货单。

利用方法是对象序列话到文件,并从文件反序列化:

public static void SaveObj<T>(T obj, string dataFile)
    
{
        FileStream FS 
= File.Create(dataFile);
        BinaryFormatter binSerializer 
= new BinaryFormatter( );
            
//序列化对象,并写到文件中
        binSerializer.Serialize(FS, obj);
        FS.Close( );
    }


public static T RestoreObj<T>(string dataFile)
    
{
        FileStream FS 
= File.OpenRead(dataFile);
        BinaryFormatter binSerializer 
= new BinaryFormatter( );
            
//从文件反序列化对象
        T obj = (T)binSerializer.Deserialize(FS);
        FS.Close( );

        
return (obj);
    }

 
dataFile参数接受一个串值,SaveObj<T>方法接受一个对象,并试图将其进行序列化到一个文件,反过来,RestoreObj<T>方法从文件中删除SaveObj<T>方法中创建的序列化对象。

以下是测试代码:
public static void TestSerialization( )
{
       
// Create a List<int> object to save/restore to/from a file.
    Console.WriteLine( );
    List
<int> test = new List<int>( );
    test.Add(
1);
    test.Add(
2);

    
// Display this object's contents and save it to a file.
    foreach (int i in test)
        Console.WriteLine(i.ToString( ));
    SaveObj
<List<int>>(test, "TEST.DATA");

    
// Restore this object from the same file and display its contents.
    List<int> testNew = new List<int>( );
    testNew 
= RestoreObj<List<int>>("TEST.DATA");
    
foreach (int i in testNew)
        Console.WriteLine(i.ToString( ));
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值