How to Ignore a property from being serialized using BinaryFormatter?

做~自己de王妃 提交于 2019-12-11 01:35:48

问题


[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";
        }
    }
}

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?


回答1:


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

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.



回答2:


Look at the NonSerializedAttribute.

[Serializable]
class DOThis
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    [NonSerialized()]
    public string Value
    {
        get
        {
            if (_name == "Hi")
                return "Hey Hi";
            else
                return "Sorry I dont know you";
        }
    }
}


来源:https://stackoverflow.com/questions/27286034/how-to-ignore-a-property-from-being-serialized-using-binaryformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!