C# dictionary 深拷贝
时间: 2023-07-12 22:35:14 浏览: 239
在 C# 中,可以使用序列化和反序列化来实现 dictionary 的深拷贝。具体的步骤如下:
1. 将 dictionary 序列化为一个字符串:
```csharp
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
public static string SerializeObject(object obj)
{
var serializer = new DataContractJsonSerializer(obj.GetType());
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
var originalDictionary = new Dictionary<string, int>();
// 添加键值对
var serializedDictionary = SerializeObject(originalDictionary);
```
2. 将字符串反序列化为一个新的 dictionary 对象:
```csharp
public static T DeserializeObject<T>(string json)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var result = (T)serializer.ReadObject(ms);
return result;
}
}
var newDictionary = DeserializeObject<Dictionary<string, int>>(serializedDictionary);
```
这样就实现了 dictionary 的深拷贝。注意,需要在 dictionary 的 value 中存储可序列化的对象。
阅读全文