簡體   English   中英

為什么[NonSerialized]在自動實現的屬性上不起作用?

[英]Why doesn't [NonSerialized] work on autoimplemented properties?

[Serializable]
class MyClass
{
    [NonSerialized] int Foo { get; set; } // error
    [NonSerialized] int bar; // ok
}

為什么不允許這樣做?

我知道諸如以下的解決方法

  • 實現ISerializable
  • 切換到XmlSerializer / XmlIgnore
  • 切換到手動執行的屬性

問題特別是為什么 [NonSerialized]不允許在屬性上使用,而在字段上允許。

屬性實際上是方法,它們不會通過二進制序列化過程進行序列化。 是被序列化的字段。 因此,僅在字段上指定NonSerialized才有意義。

我認為這是一種精細控制的情況,需要您付出更多的努力。 換句話說,默認情況下,自動屬性將具有可序列化的后備字段。 如果要使用默認值以外的任何其他內容,則不能使用自動屬性。

我以為對屬性使用[field:NonSerialized]可能有效,但無效。 C#規范未明確指出支持字段的可序列化性,但確實包含此內容(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; } }
}

因此,支持字段是可序列化的(默認值)。

如果使用的是WCF,則可能需要查看IgnoreDataMemberAttribute 這適用於自動屬性。

即使您沒有將所有其他成員都標記為DataMember (我總是覺得很痛苦)並且使用DataContract將該類標記為有效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM