如何在C#中使用自定义序列化程序序列化容器类

本文关键字:序列化 自定义 程序 容器类 | 更新日期: 2023-09-27 18:30:01

我需要序列化一些HasValue属性被求值为true的容器类。

在序列化之前,我不需要从容器列表中删除无效元素。序列化程序应该能够确定哪些对象需要序列化或不需要序列化。我想自定义序列化程序可以满足我的需要,但我不知道如何解决这个问题。任何其他解决方案/最佳实践都将不胜感激。

这是我的课程

public static class ContainerFactory
{
         public static Container Create()
         {
             var container = new Container();
             container.Persons.AddRange(new[]
                 {
                     new Person
                         {
                             FirstName = "Thomas"
                         },
                      new Person
                         {
                             FirstName = "Andrew",
                             LastName = "Martin",
                              Vehicles = new Vehicles
                                 {
                                    new Vehicle { Hsn = "65976GHR", Tsn = "HUZUKL"}
                                 }
                         },
                          new Person
                         {
                             FirstName = "Arnold",
                             LastName = "Beckmann",
                             Vehicles = new Vehicles
                                 {
                                    new Vehicle { Hsn = "345XXXHZ"},
                                    new Vehicle { Hsn = "659JUKI", Tsn = "787999HGF"}
                                 }
                         }
                 });
             return container;
         }
}
[Serializable]
public class Container
{
    public Container()
    {
        Persons = new Persons();
    }
    public Persons Persons { get; set; }
    public void Serialize()
    {
        var serializer = new XmlSerializer(typeof (Container));
        var streamWriter = new StreamWriter(@"C:'container.xml", false);
        serializer.Serialize(streamWriter, this);
    }
}
public class Persons: List<Person>
{
}
public class Vehicles: List<Vehicle>
{
    public Vehicles()
    {
    }
    public Vehicles(IEnumerable<Vehicle> vehicles):base(vehicles)
    {
    }
}
[Serializable]
public class Person : IHasValue
{
    public Person()
    {
        this.Vehicles = new Vehicles();
        this.Id = Guid.NewGuid().ToString();
    }
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Vehicles Vehicles { get; set; }
    public bool HasValue
    {
        get { return !string.IsNullOrEmpty(this.FirstName) && !string.IsNullOrEmpty(this.LastName); }
    }
}
public interface IHasValue
{
    bool HasValue { get;}
}
public class Vehicle: IHasValue
{
    public string Hsn { get; set; }
    public string Tsn { get; set; }
    public bool HasValue
    {
        get { return !string.IsNullOrEmpty(Hsn) && !string.IsNullOrEmpty(Tsn); }
    }
}
//Using the .NET XMLSerializer to test my container
Container container = ContainerFactory.Create();
container.Serialize();
Console.WriteLine("Press any Key to continue...");
Console.ReadLine(); 

输出

<?xml version="1.0" encoding="utf-8"?>
<Container xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Persons>
    <Person>
      <Id>76cdcc18-b256-40fe-b813-cd6c60e682ca</Id>
      <FirstName>Thomas</FirstName>
      <Vehicles />
    </Person>
    <Person>
      <Id>26623bf9-d799-44d2-bc1a-7ec91292d1cd</Id>
      <FirstName>Andrew</FirstName>
      <LastName>Martin</LastName>
      <Vehicles>
        <Vehicle>
          <Hsn>65976GHR</Hsn>
          <Tsn>HUZUKL</Tsn>
        </Vehicle>
      </Vehicles>
    </Person>
    <Person>
      <Id>f645cde1-10c8-4df5-81df-9b9db7712ec3</Id>
      <FirstName>Arnold</FirstName>
      <LastName>Beckmann</LastName>
      <Vehicles>
        <Vehicle>
          <Hsn>345XXXHZ</Hsn>
        </Vehicle>
        <Vehicle>
          <Hsn>659JUKI</Hsn>
          <Tsn>787999HGF</Tsn>
        </Vehicle>
      </Vehicles>
    </Person>
  </Persons>

如何实现仅为哪个HasValue == true序列化车辆/人员的目标?

如何在C#中使用自定义序列化程序序列化容器类

您需要使用:

  1. ISerializable接口-要序列化的每个类和不同节点中的每个属性都需要使用适当的属性。看看这里的例子
  2. 序列化类时,请检查HasValue == true

人员:列表<Person>也应该是Serializable。

public void GetObjectData( SerializationInfo info, StreamingContext context )    
{
    foreach (Person person in this)    
    {
        if(person.HasValue)
        {
            info.AddValue("Firsname", person, typeof(Person));
            info.AddValue (....);
            ..............
        }
    }
}