// Serialization
public string SerialSession(SessionEntity session)
{
string seSession = "";
try
{
IFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
// Serialize
formatter.Serialize(ms, session);
byte[] x = ms.ToArray();
seSession = Convert.ToBase64String(x);
ms.Close();
ms.Dispose();
}
catch (Exception ex)
{
WriteDebugLog("SerialSession", ex.ToString(), seSession);
throw;
}
return seSession;
}
public SessionEntity DeSerialSession(string seSession)
{
SessionEntity objS = null;
try
{
IFormatter formatter = new BinaryFormatter();
byte[] x = Convert.FromBase64String(seSession);
MemoryStream ms = new MemoryStream(x);
ms.Position = 0;
ms.Seek(0, SeekOrigin.Begin);
objS = (SessionEntity)formatter.Deserialize(ms);
ms.Close();
ms.Dispose();
}
catch (Exception ex)
{
WriteDebugLog("DeSerialSession", ex.ToString(), seSession);
throw;
}
return objS;
}
C# BinaryFormatter实现序列化,我们知道在.NET框架里提供了C# BinaryFormatter,那么他是如何实现序列化操作的呢,首先我们来看看C# BinaryFormatter的概念以及作用。
C# BinaryFormatter的介绍:
BinaryFormatter使用二进制格式化程序进行序列化。您只需创建一个要使用的流和格式化程序的实例,然后调用格式化程序的 Serialize 方法。流和要序列化的对象实例作为参数提供给此调用。类中的所有成员变量(甚至标记为 private 的变量)都将被序列化。
C# BinaryFormatter使用实例:
首先我们创建一个类:
1. [Serializable]
2.
3. public class MyObject {
4.
5. public int n1 = 0;
6.
7. public int n2 = 0;
8.
9. public String str = null;
10.
11.}
Serializable属性用来明确表示该类可以被序列化。同样的,我们可以用NonSerializable属性用来明确表示类不能被序列化。接着我们创建一个该类的实例,然后序列化,并存到文件里持久:
1. MyObject obj = new MyObject();
2.
3. obj.n1 = 1;
4.
5. obj.n2 = 24;
6.
7. obj.str = "一些字符串";
1. IFormatter formatter = new BinaryFormatter();
2.
3. Stream stream = new FileStream(
4. "MyFile.bin", FileMode.Create,
5. FileAccess.Write, FileShare.None);
6.
7. formatter.Serialize(stream, obj);
8.
9. stream.Close();
而将对象还原到它以前的状态也非常容易。首先,创建格式化程序和流以进行读取,然后让格式化程序对对象进行反序列化。
1. IFormatter formatter = new BinaryFormatter();
2.
3. Stream stream = new FileStream(
4. "MyFile.bin", FileMode.Open,
5. FileAccess.Read, FileShare.Read);
6.
7. MyObject obj =
8. (MyObject) formatter.Deserialize(fromStream);
9.
10.stream.Close();
11.
12.// 下面是证明
13.Console.WriteLine("n1: {0}", obj.n1);
14.Console.WriteLine("n2: {0}", obj.n2);
15.Console.WriteLine("str: {0}", obj.str);
C# BinaryFormatter实现序列化的详细内容就向你介绍到这里,希望对你了解和学习C# BinaryFormatter类有所帮助。