问题描述
我有一个名为 User
的类,它是 [Serializable]
,并且继承自基本类 IdentityUser
,是Entity Framework类和Non Serializable.
I have a class called User
and 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 :
是否有一种方法可以忽略此属性,因为我认为没有必要将'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.
通常,如果您不想序列化字段,则可以应用 [NonSerialized]
属性,而 BinaryFormatter
将跳过它.在c#7.3和更高版本中,可以通过使用以字段为目标的属性来对自动实现的属性的秘密后备字段执行此操作:
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
中的某些信息,则可以考虑实现 ISerializable
,或替换实例具有>序列化代理人.
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序列化中的未序列化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!