C 序列化和反序列化

2022-04-30 22:06:31 字數 2291 閱讀 4245

///

/// 序列化

///

/// 要序列化的物件

/// 返回存放序列化後的資料緩衝區

public static byte serialize(object data)

查閱msdn發現原來是需要序列化的class的定義需要mark it with the serializable attribute。

[serializable]

public class myobject

附上msdn關於序列化的幾點建議大致意思:

確定乙個class是否要定義為serializable 應該思考幾個問題:該類是否有誇應用程式使用的需求?是否可能被遠端使用(通過socket傳送? by youqi.)?該類的派生類是否有可能需要被序列化呢?等等。如果不確定就建議用serializable修飾,除非有以下下情況:

2.如果包含只有在當前這乙個例項中有效的特殊的成員(unmanaged memory or file handles),可用nonserialized 修飾,例項化過程中將忽略該元素;

3.如果類中資料成員包含敏感資訊,需要有選擇性的對成員進行序列化,建議implement iserializable 來實現,做法更靈活。

2、使用xmlserializer進行序列化

關於格式化器還有乙個問題,假設我們需要xml,有兩中方案:要麼編寫乙個實現iformatter介面的類,採用的方式類似於soapformatter類,但是沒有你不需要的資訊;要麼使用庫類xmlserializer,這個類不使用serializable屬性,但是它提供了類似的功能。

如果我們不想使用主流的序列化機制,而想使用xmlseralizer進行序列化我們需要做一下修改:

a.新增system.xml.serialization命名空間。

b.serializable和noserialized屬性將被忽略,而是使用xmlignore屬性,它的行為與noserialized類似。

c.xmlseralizer要求類有個預設的構造器,這個條件可能已經滿足了。

序列化:

xmlserializer xs = new xmlserializer(typeof(list));

xs.serialize(fs, listpers);

反序列化:

xmlserializer xs = new xmlserializer(typeof(list));

listlist = xs.deserialize(fs) as list;

一. 二進位制轉換成

memorystream ms = new memorystream(bytes);

ms.position = 0;

image img = image.fromstream(ms);

ms.close();

this.picturebox1.image

二. c#中byte與string的轉換**

1、system.text.unicodeencoding converter = new system.text.unicodeencoding();

byte inputbytes =converter.getbytes(inputstring);

string inputstring = converter.getstring(inputbytes);

2、string inputstring = system.convert.tobase64string(inputbytes);

byte inputbytes = system.convert.frombase64string(inputstring);

filestream filestream = new filestream(filename, filemode.open, fileaccess.read, fileshare.read);

三. c# stream 和 byte 之間的轉換

/// 將 stream 轉成 byte

public byte streamtobytes(stream stream)

/// 將 byte 轉成 stream

public stream bytestostream(byte bytes)

四. stream 和 檔案之間的轉換

將 stream 寫入檔案

public void streamtofile(stream stream,string filename)

五. 從檔案讀取 stream

public stream filetostream(string filename)

序列化和反序列化 C 序列化與反序列化。

序列化介紹 把物件用一種新的格式來表示。系列化只序列化資料。序列化不建議使用自動屬性 為什麼要序列化 將乙個複雜的物件轉換流,方便儲存與資訊交換。class program class person public int age 二進位制序列化 就是將物件變成流的過程,把物件變成byte class...

C 序列化和反序列化

binaryserialize serialize new binaryserialize book book serialize.deserialize book.write 3 測試用的 binaryserialize類 using system using system.collections...

C 序列化和反序列化

對stu類進行序列化和反序列化操作序列化所用到的stu類using system using system.collections.generic using system.linq using system.text public string stuname public int stuage ...