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

时间:2014-12-04 03:57:09

标签: c# serialization 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序列化了上面的类。下面是序列化代码,

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

这里如何忽略属性' Value'从序列化和反序列化,因为我总是可以检索'价值'财产使用'名称'属性?

2 个答案:

答案 0 :(得分:5)

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

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

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.

答案 1 :(得分:-3)

查看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";
        }
    }
}