反序列化后初始化私有只读字段

编程入门 行业动态 更新时间:2024-10-12 18:23:04
本文介绍了反序列化后初始化私有只读字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

反序列化后,我需要初始化私有只读字段。我遵循以下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.

更多推荐

反序列化后初始化私有只读字段

本文发布于:2023-10-26 07:10:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529435.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   初始化   序列化

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!