简体   繁体   English

我是否需要序列化抽象基类以使派生类可序列化

[英]Do I need to serialize the abstract base class to make the derived classes serializable

I am trying to store an object in Session variable, I have the class marked as serializable. 我正在尝试将一个对象存储在Session变量中,我将该类标记为可序列化。 This class however is derived from an abstract base class that is not serialized. 但是,该类派生自未序列化的抽象基类。 I am getting an error. 我收到一个错误。 The problem is I do not get any error in development machine but only in production and staging area which I do not have access to. 问题是我在开发机器上没有任何错误,而只是在我无法访问的生产和登台区域中。 I didn't require to serialize the class to store the object to session in my dev machine but it gave serialization error in staging environment. 我不需要序列化类来将对象存储到我的开发机中的会话中,但是在暂存环境中它给出了序列化错误。 So I marked the class as serializable and requested the deployment in staging environment. 因此,我将该类标记为可序列化,并请求在暂存环境中进行部署。 Now I am again getting the serialization error which says the base class is not marked serializable. 现在,我再次遇到序列化错误,该错误指示基类未标记为可序列化。 Do I need to serialize the base class as well. 我是否还需要序列化基类。

public abstract class A
{
    ///Properties
}
[Serializable]
public class B:A
{
      ///Properties
}

Yes, as the exception suggests: 是的,例外情况表明:

Type 'A' in Assembly '...' is not marked as serializable 程序集“ ...”中的类型“ A”未标记为可序列化

So to fix your problem - add a [Serializable] to class A too. 因此,要解决您的问题,请在A类中也添加一个[Serializable]

On the other hand, that attribute is not inherited, so if you would add it to A only, B would not be treated as Serializable. 另一方面,该属性不会被继承,因此,如果仅将其添加到A,则B不会被视为可序列化的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM