【问题标题】:How to Ignore a property from being serialized using BinaryFormatter?如何忽略使用 BinaryFormatter 序列化的属性?
【发布时间】:2014-12-04 03:57:09
【问题描述】:
[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);

如何在序列化和反序列化中忽略属性“值”,因为我总是可以使用“名称”属性检索“值”属性?

【问题讨论】:

  • 不是直接回答你的问题,但你考虑过protobuf吗?我注意到在我的性能测试中,protobuf 比 BinaryFormatter 快 方式
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# serialization binaryformatter


【解决方案1】:

您不必对代码进行任何更改: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.

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这是错误的。 NonSerialized 只能放在字段上,不能放在属性上。正确答案是BinaryFormatter已经忽略Value;它只序列化字段。
    猜你喜欢
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 2022-08-11
    • 2016-08-27
    • 2010-12-20
    相关资源
    最近更新 更多