如何忽略使用BinaryFormatter序列化的属性? [英] How to Ignore a property from being serialized using BinaryFormatter?
本文介绍了如何忽略使用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序列化的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文