我的班级看起来像这样:
public class MyClass
{
private void MyClass() { } //just to satisfy the XML serializer
public void MyClass(int a, int b)
{
A = a;
B = b;
C = a + b;
}
public int A { get; set; }
public int B { get; set; }
public int C { get; private set; } //private set is only to
//satisfy the XML Serializer
public void DoSomeMath()
{
Console.WriteLine("{0} + {1} = {2}\n", A, B, C)
}
}
当我使用& amp实例化我自己的myClass对象时,这很好用。 b参数,但反序列化器只会调用无参数的构造函数。如何在不创建其他方法的情况下初始化C并在反序列化后调用它?
答案 0 :(得分:0)
你可以简单地修改C的getter:
public int C { get { return this.A + this.B; }}
答案 1 :(得分:0)
反序列化只会填充变量 - 实例化对象所需的任何其他逻辑都需要由程序运行,而不是反序列化程序。尝试这样的事情:
public class MyClass
{
private void MyClass() // NOT just to satisfy the XML serializer
{
GetStuffReady();
}
public void MyClass(int a, int b)
{
A = a;
B = b;
GetStuffReady();
}
public int A { get; set; }
public int B { get; set; }
public int C { get; private set; }
public void GetStuffReady()
{
C = A + B;
}
public void DoSomeMath()
{
Console.WriteLine("{0} + {1} = {2}\n", A, B, C)
}
}
或者更好:
public class MyClass
{
private void MyClass() { } //just to satisfy the XML serializer
public void MyClass(int a, int b)
{
A = a;
B = b;
}
public int A { get; set; }
public int B { get; set; }
public int C
{
get
{
return A + B;
}
set { }
}
public void DoSomeMath()
{
Console.WriteLine("{0} + {1} = {2}\n", A, B, C)
}
}
编辑:如果需要在执行逻辑之前设置变量,则可以创建类的空白实例,然后使用将XML作为输入的辅助方法设置变量。请参阅以下答案以获取示例:When is the class constructor called while deserialising using XmlSerializer.Deserialize?
答案 2 :(得分:0)
如果您使用常规二进制格式化程序,则:
[OnDeserialized]
public void DoSomeMath()
{
Console.WriteLine("{0} + {1} = {2}\n", A, B, C)
}
对于XmlSerializer
,不支持事件。
您可以实施IXmlSerializable
,但这不重要。
对于DataContractSerializer
(序列化为xml),您可以尝试:
[OnDeserializing]
public void OnDeserializing(StreamingContext context)
{
... // logic here.
}
这里有XmlSerializer
的答案,但它需要继承默认的答案
How do you find out when you've been loaded via XML Serialization?