应用程序经常需要在硬盘上存储数据.以对象形式存储数据.
.NET Framework在System.Runtime.Serialization和System.runtime.Serialization.Formatters名称空间中提供了序列化对象的基础架构. 在框架中, 有一个重要的实现可用: System.Runtime.Serialization.Formatters.Binary.
这个名称空间包含的BinaryFormatter类能够将对象序列化为二进制数据, 也可以将二进制数据序列化为对象.
IFormatter接口提供了如下方法:
方法 | 说明 |
void Serialize(Stream stream, object source) | 把source序列化为stream |
object Deserialize(Stream steam) | 反序列化stream中的数据, 返回得到的对象 |
这些方法都处理流, 可以和FileStream对象联系起来.
IFormatterserializer = new BinaryFormatter();
serializer.Serialize(myStream,myObject);
反序列化同样简单:
IFormatterserializer = new BinaryFormatter();
MyObjectTypemyNewObject = serializer.Deserialize(myStream) as MyObjectType;
using System;
usingSystem.Collections.Generic;
using System.Linq;
using System.Text;
usingSystem.Threading.Tasks;
using System.IO;
usingSystem.Runtime.Serialization;
usingSystem.Runtime.Serialization.Formatters.Binary;
namespace对象的序列化和反序列化
{
class Program
{
[Serializable]
public class Product
{
public long Id;
public string Name;
public double Price;
[NonSerialized]
string Notes;
public Product(long id, stringname, double price, string notes)
{
Id = id;
Name = name;
Price = price;
Notes = notes;
}
public override string ToString()
{
return string.Format("{0}:{1} (${2:F2}) {3}", Id, Name, Price, Notes);
}
}
static void Main(string[] args)
{
try
{
//Create products.
List<Product> products =new List<Product>();
products.Add(new Product(1,"Spiky Pung", 1000.0, "Good Stuff."));
products.Add(new Product(2,"Gloop Galloop Soup", 25.0, "Tasty."));
products.Add(new Product(4,"Hat Sauce", 12.0, "One for the kids."));
Console.WriteLine("Products to save:");
foreach (Product product inproducts)
{
Console.WriteLine(product);
}
Console.WriteLine();
//Get serializer 获取序列化的接口
IFormatter serializer = newBinaryFormatter();
//Serialize products
FileStream saveFile =
newFileStream("Products.bin", FileMode.Create, FileAccess.Write);
serializer.Serialize(saveFile,products);
saveFile.Close();
//Deserilisze poducts
FileStream loadFile =
newFileStream("Products.bin", FileMode.Open, FileAccess.Read);
List<Product>savedProducts =
serializer.Deserialize(loadFile) as List<Product>;
loadFile.Close();
Console.WriteLine("Products loaded:");
foreach (Product product insavedProducts)
{
Console.WriteLine(product);
}
}
catch (SerializationException e)
{
Console.WriteLine("Aserialization exception has been thrown!");
Console.WriteLine(e.Message); ;
}
catch (IOException e)
{
Console.WriteLine("An IOexception has been thrown!");
Console.WriteLine(e.ToString());
}
Console.ReadKey();
}
}
}
.NET Framework要求把对象标记为可序列化, 才能序列化它们. 这有许多原因, 包括:
① 一些对象序列化的效果不佳. 例如, 它们需要引用只有它们本身位于内存中时才存在的本地数据.
② 一些对象包含敏感的数据, 这些数据不应该以不安全的方式保存或传送到另一个进程中. 可以使用[NonSerialized]保证不会序列化
因为序列化使用的是流, 因此能够方便操作: 诸如压缩 加密等等流操作.
---------------------- ASP.Net+Unity开发、 .Net培训、期待与您交流! ----------------------详细请查看: www.itheima.com