C 把類例項儲存到檔案裡(類的序列化和反序列化)

2022-02-25 07:12:31 字數 1626 閱讀 9101

有時候我們希望把類的例項儲存下來,以便以後的時候用。乙個直觀的方法就是streamwriter把類寫成一行,用\t分隔開每個屬性,然後用streamreader讀出來。

但是這樣太麻煩,**行數較多,而且必須事先知道屬性在行中的對應位置。這時候如果採用類序列化的方式儲存就使得**很簡單:

假如你有乙個類,在它的上面加上[serializable]屬性就可以了,表示這個類是可以序列化的

[serializable]

public class people

public int age

}

然後採用如下**將類的例項序列化到檔案中

//序列化

filestream fs = new filestream(@"d:\program\csharp\ngramtest\ngramtest\serializepeople.dat", filemode.create);

people p = new people() ;

binaryformatter bf = new binaryformatter();

bf.serialize(fs, p);

fs.close();

這樣就能夠上面的那個檔案就儲存了這個類的例項,如果想要讀出來,就可以用

//反序列化

fs = new filestream(@"d:\program\csharp\ngramtest\ngramtest\serializepeople.dat", filemode.open);

binaryformatter bf = new binaryformatter();

people p = bf.deserialize(fs) as people;

運用同樣的方法,也可以把乙個類的list完全序列化到檔案中

//序列化list

filestream fs = new filestream(@"d:\program\csharp\ngramtest\ngramtest\serializepeople.dat", filemode.create);

binaryformatter bf = new binaryformatter();

listps = new list();

ps.add(new people() );

ps.add(new people() );

bf.serialize(fs, ps);

fs.close();

讀出來的方法也是一樣的:

//反序列化list

fs = new filestream(@"d:\program\csharp\ngramtest\ngramtest\serializepeople.dat", filemode.open);

binaryformatter bf = new binaryformatter();

listps = bf.deserialize(fs) as list;

序列化可以做很多事情,這裡僅僅舉了兩個簡單的例子,很容易可以舉一反三.

把mysql查詢結果儲存到檔案的shell指令碼

該指令碼是先刪除已經存在的檔案,然後後台執行sql語句將其執行結果以一定的格式寫入檔案 複製 如下 程式設計客棧 bin bas程式設計客棧h if f www.cppcns.comvar lib mysql hell.txt then rm f var lib mysql hell.txt ech...

Python 直接儲存類例項作為序列的元素

如果我們需要儲存的資料有很多屬性,並且儲存的數量很多,可選擇定義乙個類來表示資料型別,而類的實體作為單個的成員進行儲存,這樣做的好處是可以只儲存乙個容器,而不需要每次都儲存大量的資料,並且可以限制對資料的訪問方式。1 usr bin env python2 coding utf 8 34 5 本 的...

c 類的例項

problem 設計乙個student類,類中包括 1 資料成員 sno,sname,english,computer,total,含義 學號 姓名 英語成績 計算機成績,總分 2 建構函式student int sno,string name,int english 0,computer 0 3 ...