[英]C# serialization
您好,我是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");
}
问题是,当我运行程序时,出现此错误,提示我的子类未标记为可序列化。 这是一个大项目。 我basicaly有一个学生课堂class Student : ISerializable
,这是基础课程,我有GraduateStudent : Student
和PhDStudent : Student
。 当我尝试序列化学生列表(可以是Student,GraduateStudent或PhDStudent)时,出现上述错误。 我也尝试过这样写PhDStudent : Student,ISerializable
但没有成功
如果抱怨它们没有被标记为可序列化: 则执行该操作 。 模型中的每个类型(不仅是基本类型)都必须标记为[Serializable]
。 实际上,很少需要在此处实现ISerializable
我强烈建议您不要这样做,而让序列化程序担心字段,直到您确切知道自己在做什么为止。
...因为:当您熟悉它时,您可能会发现很多原因,不要盲目使用BinaryFormatter
它可能非常脆弱,并且版本不兼容。 除非这是为了“仅需运行一次”,否则我强烈建议使用XmlSerializer
, DataContractSerializer
,json.net或protobuf-net之类的替代方法。
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;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.