【问题标题】:Why doesn't the class need to be marked with either the [DataContract] or [Serializable] attributes to be serialized?为什么类不需要用 [DataContract] 或 [Serializable] 属性标记来进行序列化?
【发布时间】:2012-01-18 15:15:52
【问题描述】:

Microsoft 在其文章“How to serialize an object to XML by using Visual C#”中提供了代码。

using System;

public class clsPerson
{
  public  string FirstName;
  public  string MI;
  public  string LastName;
}

class class1
{ 
   static void Main(string[] args)
   {
      clsPerson p=new clsPerson();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(Console.Out, p);
      Console.WriteLine();
      Console.ReadLine();
   }
}    

但是,为什么类 clsPerson 不需要使用 [DataContract] 或 [Serializable] 属性进行标记?

【问题讨论】:

标签: c# serialization


【解决方案1】:

因为XmlSerializer 不需要将这些属性放在类上。只有BinaryFormatterDataContractSerializer 可以。就此而言,DataContractSerializer 可以不用。

查看相关问题:Why is Serializable Attribute required for an object to be serialized

【讨论】:

    【解决方案2】:

    按照设计,XML 序列化使用 get AND set 访问器序列化公共字段和公共属性。序列化类型还必须具有无参数构造函数。这是唯一的合同\o/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-30
      • 2012-04-09
      • 2011-02-28
      • 2010-12-08
      • 1970-01-01
      • 2016-11-21
      • 2018-04-09
      • 1970-01-01
      相关资源
      最近更新 更多