我需要序列化一些容器类,其HasValue
属性被评估为真。
我不需要在序列化之前从容器列表中删除无效元素。序列化程序应该能够确定哪些对象需要序列化。我想自定义序列化程序可能适合我的需要,但我不知道如何解决这个问题。任何其他解决方案/最佳实践将不胜感激。
这里是我的课
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
?