[转]自定义序列化对象

None.gif 很多时候,我们需要将对象序列化成字符串保存到内存、磁盘或者 Page.ViewState 中。基于种种原因,我们希望序列化结果尽可能小,尽可能简单,即便用其他的方法(比如正则表达式)也能解析出数据。BinaryFormatter 的结果转换成字符串(或者Base64)长度太大,而 XmlSerializer 对数据类型支持有限,显然内置的序列化引擎不足以满足我们的需求,还是自己丰衣足食。
None.gif
None.gif下面的代码可能还不完善,仅供参考,内容比较简单,不做详述。
None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**/ /// <summary>
InBlock.gif
/// 序列化
ExpandedBlockEnd.gif
/// </summary>

None.gif public   static   string  SerializeObject( object  o)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  
char sep1 = '|';
InBlock.gif  
char sep2 = ',';
InBlock.gif  
char sep3 = '=';
InBlock.gif
InBlock.gif  StringBuilder sb 
= new StringBuilder();
InBlock.gif
InBlock.gif  FieldInfo[] fields 
= o.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | 
InBlock.gif    BindingFlags.NonPublic);
InBlock.gif
InBlock.gif  
foreach (FieldInfo field in fields)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    
object value = field.GetValue(o);
InBlock.gif
InBlock.gif    
if (value != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      
if (field.FieldType.GetInterface("IDictionary"!= null)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        
foreach (object key in (value as IDictionary).Keys)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif          sb.AppendFormat(
"{0}{3}{1}{2}", key, (value as IDictionary)[key], sep2, sep3);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
if (sb[sb.Length - 1== sep2) sb.Remove(sb.Length - 11);
ExpandedSubBlockEnd.gif      }

InBlock.gif      
else if (field.FieldType.GetInterface("IList"!= null)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        
foreach (object v in (value as IList))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif          sb.AppendFormat(
"{0}{1}", v, sep2);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
if (sb[sb.Length - 1== sep2) sb.Remove(sb.Length - 11);
ExpandedSubBlockEnd.gif      }

InBlock.gif      
else if (field.FieldType == typeof(Boolean))
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        sb.Append((
bool)value ? "T" : "");
ExpandedSubBlockEnd.gif      }

InBlock.gif      
else
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        sb.Append(value);
ExpandedSubBlockEnd.gif      }

ExpandedSubBlockEnd.gif    }

InBlock.gif
InBlock.gif    sb.Append(sep1);
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
if (sb[sb.Length - 1== sep1) sb.Remove(sb.Length - 11);
InBlock.gif  
return sb.ToString();
ExpandedBlockEnd.gif}

None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**/ /// <summary>
InBlock.gif
/// 反序列化
ExpandedBlockEnd.gif
/// </summary>

None.gif public   static  T DeserializeObject < T > ( string  s)
None.gif  where T : 
new ()
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  
char sep1 = '|';
InBlock.gif  
char sep2 = ',';
InBlock.gif  
char sep3 = '=';
InBlock.gif
InBlock.gif  T o 
= new T();
InBlock.gif
InBlock.gif  FieldInfo[] fields 
= o.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | 
InBlock.gif    BindingFlags.NonPublic);
InBlock.gif
InBlock.gif  
string[] values = s.Split(sep1);
InBlock.gif
InBlock.gif  
for (int i = 0; i < fields.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    FieldInfo field 
= fields[i];
InBlock.gif    
if (String.IsNullOrEmpty(values[i])) continue;
InBlock.gif
InBlock.gif    
if (field.FieldType.GetInterface("IDictionary"!= null)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      
string[] vs = values[i].Split(sep2);
InBlock.gif
InBlock.gif      IDictionary dictionary 
= field.GetValue(o) as IDictionary;
InBlock.gif
InBlock.gif      Type key 
= field.FieldType.IsGenericType ? 
InBlock.gif        field.FieldType.GetGenericArguments()[
0] : typeof(Object);
InBlock.gif      Type value 
= field.FieldType.IsGenericType ? 
InBlock.gif        field.FieldType.GetGenericArguments()[
1] : typeof(Object);
InBlock.gif
InBlock.gif      
if (dictionary == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        dictionary 
= (IDictionary)Activator.CreateInstance(field.FieldType);
InBlock.gif        field.SetValue(o, dictionary);
ExpandedSubBlockEnd.gif      }

InBlock.gif
InBlock.gif      
foreach (string v in vs)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        
string[] ns = v.Split(sep3);
InBlock.gif        dictionary.Add(Convert.ChangeType(ns[
0], key), Convert.ChangeType(ns[1], value));
ExpandedSubBlockEnd.gif      }

ExpandedSubBlockEnd.gif    }

InBlock.gif    
else if (field.FieldType.GetInterface("IList"!= null)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      
string[] vs = values[i].Split(sep2);
InBlock.gif
InBlock.gif      
if (field.FieldType.IsArray)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        Type t 
= field.FieldType.GetElementType();
InBlock.gif        Array array 
= Array.CreateInstance(t, vs.Length);
InBlock.gif
InBlock.gif        
for (int x = 0; x < vs.Length; x++)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif          array.SetValue(Convert.ChangeType(vs[x], t), x);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        field.SetValue(o, array);
ExpandedSubBlockEnd.gif      }

InBlock.gif      
else
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif        IList list 
= field.GetValue(o) as IList;
InBlock.gif
InBlock.gif        Type t 
= field.FieldType.IsGenericType ? 
InBlock.gif          field.FieldType.GetGenericArguments()[
0] : typeof(Object);
InBlock.gif
InBlock.gif        
if (list == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif          list 
= (IList)Activator.CreateInstance(field.FieldType);
InBlock.gif          field.SetValue(o, list);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
foreach (string v in vs)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif          list.Add(Convert.ChangeType(v, t));
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif      }

ExpandedSubBlockEnd.gif    }

InBlock.gif    
else if (field.FieldType == typeof(Boolean))
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      field.SetValue(o, values[i] 
== "T" ? true : false);
ExpandedSubBlockEnd.gif    }

InBlock.gif    
else if (field.FieldType.IsEnum)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      field.SetValue(o, Enum.Parse(field.FieldType, values[i], 
true));
ExpandedSubBlockEnd.gif    }

InBlock.gif    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif      field.SetValue(o, Convert.ChangeType(values[i], field.FieldType));
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
return o;
ExpandedBlockEnd.gif}

None.gif
None.gif测试代码
None.gif
None.gif[Serializable]
None.gif
public   class  MyClass
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  
private int valueType;
InBlock.gif
InBlock.gif  
public int ValueType
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
get dot.gifreturn valueType; }
ExpandedSubBlockStart.gifContractedSubBlock.gif    
set dot.gif{ valueType = value; }
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private object obj;
InBlock.gif
InBlock.gif  
public object Object
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
get dot.gifreturn obj; }
ExpandedSubBlockStart.gifContractedSubBlock.gif    
set dot.gif{ obj = value; }
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private bool boolean;
InBlock.gif
InBlock.gif  
public bool Boolean
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
get dot.gifreturn boolean; }
ExpandedSubBlockStart.gifContractedSubBlock.gif    
set dot.gif{ boolean = value; }
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private string[] array;
InBlock.gif
InBlock.gif  
public string[] Array
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
get dot.gifreturn array; }
ExpandedSubBlockStart.gifContractedSubBlock.gif    
set dot.gif{ array = value; }
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private List<string> list;
InBlock.gif
InBlock.gif  
public List<string> List
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
get dot.gifreturn list; }
ExpandedSubBlockStart.gifContractedSubBlock.gif    
set dot.gif{ list = value; }
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private ArrayList arrayList;
InBlock.gif
InBlock.gif  
public ArrayList ArrayList
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
get dot.gifreturn arrayList; }
ExpandedSubBlockStart.gifContractedSubBlock.gif    
set dot.gif{ arrayList = value; }
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private Hashtable hashtable;
InBlock.gif
InBlock.gif  
public Hashtable Hashtable
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
get dot.gifreturn hashtable; }
ExpandedSubBlockStart.gifContractedSubBlock.gif    
set dot.gif{ hashtable = value; }
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
private Dictionary<stringint> dictionary;
InBlock.gif
InBlock.gif  
public Dictionary<stringint> Dictionary
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
get dot.gifreturn dictionary; }
ExpandedSubBlockStart.gifContractedSubBlock.gif    
set dot.gif{ dictionary = value; }
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
None.gif
class  Program
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif  
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif    
//Test();
InBlock.gif

InBlock.gif    MyClass o 
= new MyClass();
InBlock.gif    o.List 
= new List<string>();
InBlock.gif    o.Dictionary 
= new Dictionary<stringint>();
InBlock.gif    o.ArrayList 
= new ArrayList();
InBlock.gif    o.Hashtable 
= new Hashtable();
InBlock.gif
InBlock.gif    o.ValueType 
= 123456;
InBlock.gif    o.Object 
= DateTime.Now;
InBlock.gif    o.Boolean 
= true;
InBlock.gif
InBlock.gif    o.Dictionary.Add(
"dict1"1);
InBlock.gif    o.Dictionary.Add(
"dict2"2);
InBlock.gif    
ExpandedSubBlockStart.gifContractedSubBlock.gif    o.Array 
= new string[] dot.gif"array1""array2""array3" };
InBlock.gif    
InBlock.gif    o.List.Add(
"list1");
InBlock.gif    o.List.Add(
"list2");
InBlock.gif    
InBlock.gif    o.ArrayList.Add(
"ArrayList1");
InBlock.gif    o.ArrayList.Add(
"ArrayList2");
InBlock.gif    
InBlock.gif    o.Hashtable.Add(
"Hashtable1"1);
InBlock.gif    o.Hashtable.Add(
"Hashtable2"2);
InBlock.gif
InBlock.gif    
// SerializeObject
InBlock.gif

InBlock.gif    
string s = SerializeObject(o);
InBlock.gif    Console.WriteLine(s);
InBlock.gif
InBlock.gif    MyClass m 
= DeserializeObject<MyClass>(s);
InBlock.gif    Console.WriteLine(SerializeObject(m));
InBlock.gif
InBlock.gif    
// BinaryFormatter
InBlock.gif

InBlock.gif    BinaryFormatter binary 
= new BinaryFormatter();
InBlock.gif    MemoryStream stream 
= new MemoryStream();
InBlock.gif    binary.Serialize(stream, o);
InBlock.gif    s 
= Convert.ToBase64String(stream.ToArray());
InBlock.gif    Console.WriteLine(s);
ExpandedSubBlockEnd.gif  }

ExpandedBlockEnd.gif}

None.gif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值