シリアル化/逆シリアル化する必要があるクラスがあり、途中まで来ています。シリアル化が機能しているため、以下の XML が生成されます。ただし、私は自分自身を実装しているので、明示的な実装ではなく属性ベースのフラグを使用してシリアル化されていることを考えるとIXmlSerializable
、の実装がReadXml
どのように見えるべきかはわかりません。SomeGenericClass<T>
IXmlSerializable
<?xml version="1.0" encoding="utf-16"?>
<FooContainer FooName="DoSomething">
<SomeGenericClassOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Value="Foobar" Name="firstParam" Description="First Paramater Serialized" />
<SomeGenericClassOfInt32 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Value="10000" Name="nextParam" Description="Second Serialized parameter" />
</FooContainer>
次のインスタンスにシリアライズしたい:
public class FooContainer : IList<ISomeGenericClassBase>, IXmlSerializable
{
public string FooName {get;set;}
void IXmlSerializable.WriteXml(XmlWriter writer) {
var serializer = XmlSerializer.FromTypes(new Type[]{SomeGenericBaseClass})[0];
this
.Select(item=>SomeGenericClassBase.ConvertToMe(item))
.ToList()
.ForEach(item=>serializer.Serialize(writer, item));
}
// IList Implementation omitted - wraps a private List<ISomeGenericClassBase>
}
リストには、次の行に沿ったインスタンスが含まれます。
public interface ISomeGenericClassBase
{
}
public interface ISomeGenericBaseClass<T> : ISomeGenericBaseClass
{
}
public class SomeGenericClassBase : ISomeGenericClassBase
{
public static SomeGenericClassBase ConvertToMe(ISomeGenericClassBase target) {
return new SomeGenericClassBase() {Property1 = target.Property1; Property2 = target.Property2}
}
public static ISomeGenericBaseClass ExpantToTyped(SomeGenericClassBase target) {
// Implementation omitted - converts a base class instance to a generic instance by working out the generic type from saved data and reconstructing
}
}
public class SomeGenericClass<T> : SomeGenericClassBase, ISomeGenericBaseClass<T>
{
[XmlAttribute]
public string Name {get;set;}
[XmlAttribute]
public string Description{get;set;}
[XmlAttribute]
public T Value {get;set;}
[XmlElement("")]
public T[] ValidOptions {get;set;}
}
編集:実装を拡張しました-そのままでは、問題を正しく説明していませんでした
SomeGenericClassBase
コアの問題は、インスタンスを取得するだけであっても、インターフェイスのみを実装するアイテムをシリアル化できるようにしたいということです。メソッドで使用されているアプローチExpandToTyped
に従って、クラスのコンシューマーが実装に十分なデータを保存して、結果のクラスを必要に応じて元の形式に変換できるようにすることを期待しています。確かに、忠実度は失われますが、基本クラスのリストの代わりにインターフェイスのリストを使用するという柔軟性と引き換えに、私はそれを受け入れることができます。