忽略BinaryFormatter序列化中的未序列化属性 [英] Ignore Non Serialized property in BinaryFormatter Serialization

查看:150
本文介绍了忽略BinaryFormatter序列化中的未序列化属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 User 的类,它是 [Serializable] ,并且继承自基本类 IdentityUser ,是Entity Framework类和Non Serializable.

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

我在 Booking 类中有一个类型为 User 的属性,并且 Booking 类是 Serializable 我正在尝试使用 BinaryFormatter 序列化预订对象,但是由于 IdentityUser 类,我无法这样做,但出现此错误:

I have a property in Booking class with type User and Booking class is Serializable I am trying to serialize the booking object using BinaryFormatter but I can't because of IdentityUser class and I get this error :

在"中键入"Microsoft.AspNet.Identity.EntityFramework.IdentityUser"程序集'Microsoft.AspNet.Identity.EntityFramework,Version = 2.0.0.0,文化=中性,PublicKeyToken = 31bf3856ad364e35'未标记为可序列化.'

'Type 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser' in Assembly 'Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.'

是否有一种方法可以忽略此属性,因为我认为没有必要将'IdentityUser'设置为Serializable.

Is there a way to ignore this property because I don't think there is away to make 'IdentityUser' as Serializable.

[Serializable]
public class User : IdentityUser
{
   public String FirstName { get; set; }
}

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

推荐答案

BinaryFormatter 序列化自动实现属性秘密支持字段是实际序列化的内容.

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

请参阅: C#7.3的新功能.

在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; } }
}

顺便说一句,如果您需要序列化 User 中的某些信息,则可以考虑实现>序列化代理人.

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.

这篇关于忽略BinaryFormatter序列化中的未序列化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆