保存数据结构在C# [英] Saving Data Structures in C#
问题描述
我写一个家庭图书馆管理者学习C#。
I'm learning C# by writing a home library manager.
我将书存放在一个数据结构,并对其执行操作的BookController的。
I have a BookController that will store the books in a data structure and perform operations on them.
C#有在字典中的数据保存到本地文件也许是在一个XML时尚的一种方式后加载,还是我将不得不写自己?
Does C# have a way of saving the data in the dictionary to a local file perhaps in an XML fashion to load later, or am I going to have to write it myself?
什么是保存和加载提供给C#这个数据的最好的方法?只是需要指出的好的方向发展。
What is the best method of saving and loading this data available to C#? Just need pointed in a good direction.
推荐答案
事实上,C#(语言)不知道的任何关于serailization,但.NET(框架)提供了很多方法... 的XmlSerializer
,的BinaryFormatter
,的DataContractSerializer
(.NET 3.0) - 或有一些定制的序列化框架太
Actually, C# (the language) doesn't know anything about serailization, but .NET (the framework) provides lots of ways... XmlSerializer
, BinaryFormatter
, DataContractSerializer
(.NET 3.0) - or there are a few bespoke serialization frameworks too.
要使用哪一个取决于你要求; 的BinaryFormatter
使用简单,但烧伤集元数据信息存入文件 - 使之成为非便携式(你不能在Java中打开它,例如)。 的XmlSerializer
和的DataContractSerializer
主要是基于XML的,使得它非常便携,但相当大,除非你压缩。
Which to use depends on your requirements; BinaryFormatter
is simple to use, but burns assembly metadata information into the file - making it non-portable (you couldn't open it in Java, for example). XmlSerializer
and DataContractSerializer
are primarily xml-based, making it quite portable, but fairly large unless you compress it.
一些专有的序列化两者之间中途; protobuf网是一个二进制格式化(所以非常密集的数据),但它遵循用于数据的便携式标准格式(谷歌的协议缓冲区SPEC)。无论这是非常有用取决于您的方案
Some proprietary serializers are half-way between the two; protobuf-net is a binary formatter (so very dense data), but which follows a portable standard for the data format (Google's protocol buffers spec). Whether this is useful depends on your scenario.
典型的编码(这里使用的XmlSerializer
):
Typical code (here using XmlSerializer
):
XmlSerializer ser = new XmlSerializer(typeof(Foo));
// write
using (var stream = File.Create("foo.xml"))
{
ser.Serialize(stream, foo); // your instance
}
// read
using (var stream = File.OpenRead("foo.xml"))
{
Foo newFoo = (Foo)ser.Deserialize(stream);
}
这篇关于保存数据结构在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!