我有一个类型,有多个构造函数,但我无法控制它,其中一个构造函数如下:
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
的定义?此外,这种类型是我真正需要序列化的对象定义中的一个重要部分。