Ignore Non Serialized property in BinaryFormatter Serialization

后端 未结 1 1707
时光说笑
时光说笑 2021-02-09 03:23

I have a class called Userand it is [Serializable] and inherited from base class IdentityUser an Entity Framework class and Non Serializab

相关标签:
1条回答
  • 2021-02-09 04:03

    BinaryFormatter serializes the public and private fields of a object -- not the properties. For an auto-implemented property the secret backing field is what is actually serialized.

    Normally, if you do not want a field to be serialized, you can apply the [NonSerialized] attribute, and BinaryFormatter will skip it. In c# 7.3 and later, it's possible to do this to the secret backing field of an auto-implemented property by using a field-targeted attribute:

        [field: NonSerialized]
        public virtual User Guest { set; get; }
    

    See: Auto-Implemented Property Field-Targeted Attributes and What's new in C# 7.3.

    Prior to c# 7.3 there is no way to apply an attribute to the backing field of an auto-implemented property. Thus you need to make the backing field be explicit:

    [Serializable]
    public class Booking
    {
        [ForeignKey("Guest")]
        public string GuestId { set; get; }
    
        [NonSerialized]
        User guest;
    
        public virtual User Guest { set { guest = value; } get { return guest; } }
    }
    

    Incidentally, if you need to serialize some of the information in User, you could consider implementing ISerializable, or replacing instances of User with serialization surrogates.

    0 讨论(0)
提交回复
热议问题