如何忽略使用BinaryFormatter序列化的属性?

编程入门 行业动态 更新时间:2024-10-10 07:24:18
本文介绍了如何忽略使用BinaryFormatter序列化的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 [Serializable] class DOThis { private string _name; public string Name { get { return _name; } set { _name = value; } } public string Value { get { if (_name == "Hi") return "Hey Hi"; else return "Sorry I dont know you"; } } }

我有上述要使用BinaryFormatter序列化的类.下面是序列化代码,

I have the above class to be serialized using BinaryFormatter. Below is the serialization code,

DOThis obj = new DOThis(); obj.Name = "Ho"; BinaryFormatter bfm = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bfm.Serialize(ms, obj);

在这里如何忽略序列化和反序列化的值"属性,因为我始终可以使用名称"属性来检索值"属性?

Here how to ignore the property 'Value' from being serialized and also in deserialize, as I can always retrieve 'Value' property using 'Name' property?

推荐答案

您不必对代码进行任何更改:BinaryFormatter仅序列化字段,而不对属性进行序列化,因此不会对Value进行序列化.

You don't have to make any changes to your code: BinaryFormatter only serializes fields, not properties, so it won't serialize Value.

这是结果MemoryStream的十六进制转储,显示仅序列化了"_name"和"Ho":

Here's a hex dump of the resulting MemoryStream which shows that only "_name" and "Ho" are serialized:

00 01 00 00 00 FF FF FF FF 01 00 00 00 00 00 00 .....ÿÿÿÿ....... 00 0C 02 00 00 00 3B 44 65 6D 6F 2C 20 56 65 72 ......;Demo, Ver 73 69 6F 6E 3D 31 2E 30 2E 30 2E 30 2C 20 43 75 sion=1.0.0.0, Cu 6C 74 75 72 65 3D 6E 65 75 74 72 61 6C 2C 20 50 lture=neutral, P 75 62 6C 69 63 4B 65 79 54 6F 6B 65 6E 3D 6E 75 ublicKeyToken=nu 6C 6C 05 01 00 00 00 0B 44 65 6D 6F 2E 44 4F 54 ll......Demo.DOT 68 69 73 01 00 00 00 05 5F 6E 61 6D 65 01 02 00 his....._name... 00 00 06 03 00 00 00 02 48 6F 0B ........Ho.

更多推荐

如何忽略使用BinaryFormatter序列化的属性?

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

发布评论

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

>www.elefans.com

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