-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathXmlSerializerHelper.cs
More file actions
66 lines (65 loc) · 1.92 KB
/
XmlSerializerHelper.cs
File metadata and controls
66 lines (65 loc) · 1.92 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
using System.IO;
using System.Xml.Serialization;
namespace Helper.Core.Library
{
public class XmlSerializerHelper
{
/// <summary>
/// 实体类型数据序列化成字节数组
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="t">实体类型数据</param>
/// <returns></returns>
public static byte[] Serialize<T>(T t) where T : class
{
MemoryStream memoryStream = null;
try
{
byte[] bytes = null;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (memoryStream = new MemoryStream())
{
xmlSerializer.Serialize(memoryStream, t);
bytes = memoryStream.ToArray();
}
return bytes;
}
catch
{
throw;
}
finally
{
if (memoryStream != null) memoryStream.Dispose();
}
}
/// <summary>
/// 字节数组反序列化成实体类型数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="bytes"></param>
/// <returns></returns>
public static T Deserialize<T>(byte[] bytes) where T : class
{
MemoryStream memoryStream = null;
try
{
T t = null;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (memoryStream = new MemoryStream(bytes))
{
t = xmlSerializer.Deserialize(memoryStream) as T;
}
return t;
}
catch
{
throw;
}
finally
{
if (memoryStream != null) memoryStream.Dispose();
}
}
}
}