【问题标题】:C# serializationC# 序列化
【发布时间】:2013-11-27 19:46:07
【问题描述】:

您好,我是 C# 新手,我正在尝试序列化一些数据。我有一个基类,它实现了ISerializable 和更多扩展基类的子类。在我的基类中,我写了这个:

protected BaseClass(SerializationInfo info, StreamingContext context)
{
    if (info == null)
        throw new System.ArgumentNullException("info");
 }

[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
    if (info == null)
        throw new System.ArgumentNullException("info");
}

问题是当我运行我的程序时,我得到这个错误,说我的子类没有被标记为可序列化。 这是一个大工程。我基本上有一个学生班class Student : ISerializable,这是基类,我有GraduateStudent : StudentPhDStudent : Student。当我尝试序列化学生列表(可以是 Student、GraduateStudent 或 PhDStudent)时,出现上述错误。我也试过这样写PhDStudent : Student,ISerializable但没有成功

【问题讨论】:

  • 然后标记为[Serializable] :)
  • 我已经这样做了,但我得到了同样的错误
  • 我们只能使用给出的信息和示例。请在上面的示例中包含它。
  • 信息很清楚:标记子类型。但是:我强烈向您建议 BinaryFormatter 会在这里伤害您
  • 我已经写了更多关于它的信息并更新了问题

标签: c# serialization


【解决方案1】:

如果它抱怨它们没有被标记为可序列化:那就这样做模型中的每个类型(不仅仅是基本类型)都必须标记为[Serializable]。实际上,您很少需要在这里实现ISerializable - 我强烈建议您不要这样做,让序列化程序担心这些字段,直到您确切知道自己在做什么......

...因为:当您熟悉它时,您可能会找到很多不盲目使用BinaryFormatter 的理由——它可能非常脆弱并且版本不兼容。除非这是为了“只需要运行一次”,否则我强烈建议使用 XmlSerializerDataContractSerializer、json.net 或 protobuf-net 等替代方案。

【讨论】:

    【解决方案2】:
    public abstract class BaseClass
    {
    
    }
    
    public class Child1:BaseClass
    {
    
    }
    
    public class Child2:BaseClass
    {
    
    }
    
    public class SeriliazerTest
    {
            // You have to define them here, otherwise they will not be found
            [XmlArrayItem(Type = typeof(Child1), ElementName = "Child1")]
            [XmlArrayItem(Type = typeof(Child2), ElementName = "Child2")] 
            public BaseClass[] Child {get;set;}
     }
    

    【讨论】:

    • ISerializable 和异常消息建议 BinaryFormatter。实际上,这甚至在 XnlSerializer 中都无法正常工作 - 它缺少 XmlIncludeAttribute 标记
    • 谢谢@MarcGravell 对不起,我没有看到他想要 BinaryFormatter 今天对我来说是糟糕的一天,我无法获得任何分数,哈哈
    • 其实我从来没想过这么复杂。我只想序列化我的学生名单。在 java 中我很容易做到这一点,但 C# 让我很头疼
    • @user3043278 那么为什么你不只是使用非常简单且易于阅读的 XML 序列化程序,我应该为你发布一个示例。
    • 这是我在 msdn 上找到的,所以我认为它会起作用。也许一个简单的例子会有所帮助
    猜你喜欢
    • 2013-10-12
    • 2011-05-12
    • 1970-01-01
    • 2014-12-30
    • 2012-02-02
    • 2016-06-15
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多