I need to initialize private readonly field after Deserialization. I have folowing DataContract:
[DataContract]
public class Item
{
public Item()
{
// Constructor not called at Deserialization
// because of FormatterServices.GetUninitializedObject is used
// so field will not be initialized by constructor at Deserialization
_privateReadonlyField = new object();
}
// Initialization will not be called at Deserialization (same reason as for constructor)
private readonly object _privateReadonlyField = new object();
[DataMember]
public string SomeSerializableProperty { get; set; }
[OnDeserializing]
public void OnDeserializing(StreamingContext context)
{
// With this line code even not compiles, since readonly fields can be initialized only in constructor
_privateReadonlyField = new object();
}
}
All what I need, that after Deserialization _privateReadonlyField is not null.
Any suggestions about this - is it possible at all?
Or I need to remove "readonly" key, which is not a good option.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…