【发布时间】:2014-07-10 14:07:27
【问题描述】:
我有一个类型,我不能用多个构造函数控制,相当于这个:
public class MyClass
{
private readonly string _property;
private MyClass()
{
Console.WriteLine("We don't want this one to be called.");
}
public MyClass(string property)
{
_property = property;
}
public MyClass(object obj) : this(obj.ToString()) {}
public string Property
{
get { return _property; }
}
}
现在,当我尝试反序列化它时,会调用私有无参数构造函数,并且永远不会设置该属性。测试:
[Test]
public void MyClassSerializes()
{
MyClass expected = new MyClass("test");
string output = JsonConvert.SerializeObject(expected);
MyClass actual = JsonConvert.DeserializeObject<MyClass>(output);
Assert.AreEqual(expected.Property, actual.Property);
}
给出以下输出:
We don't want this one to be called.
Expected: "test"
But was: null
如何在不更改MyClass 定义的情况下修复它?此外,这种类型是我真正需要序列化的对象定义中的一个关键。
【问题讨论】: