-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerializeHelper.cs
More file actions
131 lines (124 loc) · 2.77 KB
/
Copy pathSerializeHelper.cs
File metadata and controls
131 lines (124 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Reflection;
using System.Collections;
namespace GDSerializeHelper
{
public class SerializeHelper
{
public static object Deserialize(Hashtable data)
{
if (data == null)
return null;
Type type=Type.GetType(data[(byte)255] as string);
data.Remove((byte)255);
object obj;
if(type.IsArray)
{
obj=Array.CreateInstance(type.GetElementType(),data.Count);
for(int i=0;i<data.Count;i++)
{
object item=data[(byte)i];
if(NeedDeserialize(item))
{
item=Deserialize(item as Hashtable);
}
(obj as Array).SetValue(item,i);
}
}
else
{
obj=type.Assembly.CreateInstance(type.FullName);
if(obj is ICollection)
{
if(obj is IList)
{
for (int i = 0; i < data.Count;i++ )
{
object item=data[(byte)i];
if(NeedDeserialize(item))
{
item=Deserialize(item as Hashtable);
}
(obj as IList).Add(item);
}
}
}
else
{
PropertyInfo[] propertyInfos=type.GetProperties();
for(int i=0; i<propertyInfos.Length;i++)
{
if(data.ContainsKey((byte)i))
{
object item=data[(byte)i];
if(NeedDeserialize(item))
{
item=Deserialize(item as Hashtable);
}
propertyInfos[i].SetValue(obj,item,null);
}
}
}
}
return obj;
}
public static Hashtable Serialize(object obj)
{
if (obj == null)
return null;
Hashtable data=new Hashtable();
data[(byte)255]=obj.GetType().FullName;
if(obj is ICollection)
{
int index=0;
foreach(object item in ((IEnumerable)obj))
{
if(NeedSerialize(item))
{
data[(byte)index++]=Serialize(item);
}
else
{
data[(byte)index++]=item;
}
}
}
else
{
PropertyInfo[] propertyInfos=obj.GetType().GetProperties();
for(int i=0;i<propertyInfos.Length;i++)
{
if(propertyInfos[i].GetAccessors().Length==2)
{
object item=propertyInfos[i].GetValue(obj,null);
if(item!=null)
{
if(NeedSerialize(item))
{
data[(byte)i]=Serialize(item);
}
else
{
data[(byte)i]=item;
}
}
}
}
}
return data;
}
public static bool NeedSerialize(object obj)
{
if (obj == null) return false;
return !(obj.GetType().IsPrimitive || obj is string ||
obj is byte[]|| obj is int[]||obj is Hashtable || obj.GetType().IsEnum);
}
public static bool NeedDeserialize(object obj)
{
return obj is Hashtable&& (obj as Hashtable).ContainsKey((byte)255);
}
}
}