List を Xml に動的にシリアル化しようとしています。T のプロパティとして ICollection を持っていない限り、そうすることができます。
Xml に書き込む前に、ICollection 型を List に動的に上書きしたいと思います。
これは私がこれまでに持っているものです。
List<-XmlElementAttribute-> attrToConvertList = new List<-XmlElementAttribute->();
foreach (var propertyInfo in typeof(T).GetProperties())
{
if (propertyInfo.PropertyType.Name == "ICollection`1")
{
XmlElementAttribute attrToConvert = new XmlElementAttribute();
attrToConvert.ElementName = propertyInfo.Name;
attrToConvert.Type = typeof(List<>);
attrToConvert.Type = attrToConvert.Type.MakeGenericType(propertyInfo.PropertyType.GetGenericArguments()[0]);
attrToConvertList.Add(attrToConvert);
}
}
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attributesToConvert = new XmlAttributes();
foreach (var xmlElementAttribute in attrToConvertList)
attributesToConvert.XmlElements.Add(xmlElementAttribute);
overrides.Add(typeof(T), attributesToConvert);
XmlSerializer serializer = new XmlSerializer(typeof(List<T>), overrides);
インターフェイスであるため、タイプ ICollection をシリアル化できないというエラーが表示されます。私が XmlAttributeOverrides で行っていたことは、ICollection を List 型に上書きすることになっているという印象を受けました。