反序列化后,我需要初始化私有只读字段。我遵循以下DataContract:
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(); } }我需要的是,反序列化后_privateReadonlyField不是
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.
推荐答案任何声明为 private只读可以在声明时所在的同一行中或在构造函数中实例化。完成后就无法更改。
Any field declared as private readonly can be instantiated in the same line where it was declared or inside a constructor. Once that is done it cannot be changed.
来自 MSDN :
readonly关键字是一个修饰符,您可以在字段上使用。当字段声明包含只读修饰符时,对声明引入的字段的赋值只能作为声明的一部分或在同一类的构造函数中进行。
The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
这意味着您必须删除只读关键字才能使其正常工作。
That means that you will have to remove readonly keyword to get it to work.
更多推荐
反序列化后初始化私有只读字段
发布评论