代码之家  ›  专栏  ›  技术社区  ›  Stefan Monov

为什么[NonSerialized]不能处理自动实现的属性?

  •  6
  • Stefan Monov  · 技术社区  · 15 年前
    [Serializable]
    class MyClass
    {
        [NonSerialized] int Foo { get; set; } // error
        [NonSerialized] int bar; // ok
    }
    

    为什么这是不允许的?

    我知道解决办法,比如

    • 实现ISerializable
    • 切换到XmlSerializer/XmlIgnore
    • 切换到手动实现的属性

    问题是具体的 为什么? 在属性上不允许[非序列化],但在字段上允许。

    3 回复  |  直到 15 年前
        1
  •  12
  •   Thomas Levesque    15 年前

    属性实际上是方法,它们不是由二进制序列化过程序列化的。是字段被序列化了。所以只有明确说明 NonSerialized 在球场上。

        2
  •  3
  •   Tim Cooper    14 年前

    我认为这是一种细粒度控制的情况,需要您付出更多的努力。换句话说,自动属性在默认情况下将具有可序列化的支持字段。如果您想要的不是默认值,那么就不能使用自动属性。

    [field:NonSerialized] 反对财产可能有效,但事实并非如此。规范没有显式地调用backing字段的可序列化性,但它确实包含以下内容(10.7.3):

    The following example:
     public class Point {
        public int X { get; set; } // automatically implemented
        public int Y { get; set; } // automatically implemented
    }
    is equivalent to the following declaration:
    public class Point {
        private int x;
        private int y;
        public int X { get { return x; } set { x = value; } }
        public int Y { get { return y; } set { y = value; } }
    }
    

        3
  •  0
  •   Simon_Weaver    13 年前

    你可以看看 IgnoreDataMemberAttribute 如果你用的是WCF。这适用于自动属性。

    即使您没有将所有其他成员标记为 DataMember (我总是觉得很痛苦)和 DataContract

    推荐文章