一个自定义类,继承了Dictionary<string,string>和ICloneable,此类还有自己的属性字段,在用BinaryFormatter实现深度克隆时字典数据可以克隆到,但自己的属性字段克隆丢失了,求解决办法,谢谢啦,代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
var obj = new TestClone(); obj.Add("testKey", "testValue");
obj.Name = "this is a test string property"; //克隆新实例
var newObj = (TestClone)obj.Clone(); //字典内容克隆成功
foreach (var key in newObj.Keys)
{
Console.WriteLine(string.Format("key:{0},value:{1}", key, newObj[key]));
} //属性没有克隆成功
Console.WriteLine(newObj.Name); Console.ReadLine();
} } [Serializable]
public class TestClone : Dictionary<string, string>, ICloneable
{
//测试用属性
public string Name { get; set; }
public TestClone()
{
} public TestClone(SerializationInfo info, StreamingContext context)
: base(info, context)
{
} #region ICloneable 成员 public object Clone()
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Position = 0;
var newObj = formatter.Deserialize(stream);
return newObj;
}
} #endregion
}
}