C#字典可以序列化吗
时间: 2024-10-11 12:13:02 浏览: 34
当然可以。C#中的`Dictionary<TKey, TValue>`数据结构是可以序列化的,这通常通过.NET框架提供的序列化机制来完成。你可以使用`System.Runtime.Serialization.Formatters.Binary.BinaryFormatter`或`System.IO.StreamWriter`配合`BinarySerializer`来进行二进制序列化,也可以使用`System.Xml.Serialization.XmlSerializer`进行XML序列化。例如:
```csharp
using System.IO;
using System.Runtime.Serialization;
// 对字典进行序列化
byte[] serializedDict = null;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, dictionary);
serializedDict = ms.ToArray();
}
// 反序列化
Dictionary<TKey, TValue> deserializedDict = null;
using (MemoryStream ms = new MemoryStream(serializedDict))
{
BinaryFormatter formatter = new BinaryFormatter();
deserializedDict = (Dictionary<TKey, TValue>)formatter.Deserialize(ms);
}
```
或者使用XML序列化:
```csharp
using System.Xml.Serialization;
XmlSerializer serializer = new XmlSerializer(typeof(Dictionary<TKey, TValue>));
string xmlString = "";
using (TextWriter writer = new StringWriter(xmlString))
{
serializer.Serialize(writer, dictionary);
}
// 反序列化
Dictionary<TKey, TValue> deserializedDict = (Dictionary<TKey, TValue>)serializer.Deserialize(new StringReader(xmlString));
```
阅读全文