自定義序列化物件

2021-09-05 18:51:38 字數 2434 閱讀 3236

很多時候,我們需要將物件序列化成字串儲存到記憶體、磁碟或者 page.viewstate 中。基於種種原因,我們希望序列化結果盡可能小,盡可能簡單,即便用其他的方法(比如正規表示式)也能解析出資料。binaryformatter 的結果轉換成字串(或者base64)長度太大,而 xmlserializer 對資料型別支援有限,顯然內建的序列化引擎不足以滿足我們的需求,還是自己豐衣足食。

下面的**可能還不完善,僅供參考,內容比較簡單,不做詳述。

///

/// 序列化

///

public static string serializeobject(object o)

if (sb[sb.length - 1] == sep2) sb.remove(sb.length - 1, 1); }

else if (field.fieldtype.getinte***ce("ilist") != null)

if (sb[sb.length - 1] == sep2) sb.remove(sb.length - 1, 1); }

else if (field.fieldtype == typeof(boolean))

else

} }

if (sb[sb.length - 1] == sep1) sb.remove(sb.length - 1, 1);

return sb.tostring(); }

///

/// 反序列化

///

public static t deserializeobject(string s)

where t : new()

foreach (string v in vs)

} else if (field.fieldtype.getinte***ce("ilist") != null)

field.setvalue(o, array); }

else

foreach (string v in vs)

} }

else if (field.fieldtype == typeof(boolean))

else if (field.fieldtype.isenum)

else

} return o; }

測試**

[serializable]

public class myclass

set }

private object obj;

public object object

set }

private bool boolean;

public bool boolean

set }

private string array;

public string array

set }

private listlist;

public listlist

set }

private arraylist arraylist;

public arraylist arraylist

set }

private hashtable hashtable;

public hashtable hashtable

set }

private dictionarydictionary;

public dictionarydictionary

set }

}class program ;

o.list.add("list1");

o.list.add("list2");

o.arraylist.add("arraylist1");

o.arraylist.add("arraylist2");

o.hashtable.add("hashtable1", 1);

o.hashtable.add("hashtable2", 2);

// serializeobject

string s = serializeobject(o);

console.writeline(s);

myclass m = deserializeobject(s);

console.writeline(serializeobject(m));

// binaryformatter

binaryformatter binary = new binaryformatter();

memorystream stream = new memorystream();

binary.serialize(stream, o);

s = convert.tobase64string(stream.toarray());

console.writeline(s); }

}

qt序列化自定義物件 Qt序列化

class painting public painting painting const qstring title,const qstring artist,int year qstring title const private qstring mytitle qstring myartist...

可序列化和自定義序列化

序列化技術的主要兩個目的是 持久化儲存 按值封送。net framework支援三種序列化器 binary xml soap.他們各有優缺點,分別列如下 1.binary序列化是完全保真的,因為除非特殊宣告為nonserialized,那麼所有成員 包括私有的和公有的 都會被序列化。該序列化器的結果...

Serializable 自定義序列化

序列化物件可以自定義序列化,也可以使用預設序列化 如何選擇呢?這就要從序列化的目的說起,序列化的目的簡單來說就是儲存,之後可以還原,這就是說只要我們能達到這個目的,都是ok的。如果都ok那麼就可以選擇更ok的形式。看下面這個例子 oddnum 這是乙個極其沒有道理的例子,只是為了說明問題 publi...