我们假设有以下通用集合:
public class MyCollection<T> : IEnumerable<T>
{
IEnumerable<T> _items;
public bool MySpecialProperty { get; set; }
public MyCollection(IEnumerable<T> collection)
{
_items = collection;
}
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _items.GetEnumerator();
}
}
我尝试按DataContractSerializer
使用
MyCollection<int> original = new MyCollection<int>(new int[] { 1, 2, 3 })
{
MySpecialProperty = false
};
DataContractSerializer serializer = new DataContractSerializer(typeof(MyCollection<int>));
var builder = new StringBuilder();
using (XmlWriter writer = XmlTextWriter.Create(builder))
{
serializer.WriteObject(writer, original);
}
var serialized = builder.ToString();
我知道,可以使用DataContractAttribute
作为集合定义,使用DataMemberAttribute
作为_items
和MySpecialProperty
成员。但有没有办法将我的类序列化为普通集合?所以,我期待以下XML:
<MyCollection>
<Item>1</Item>
<Item>2</Item>
<Item>3</Item>
<MySpecialProperty>false</MySpecialProperty>
</MyCollection>
我曾尝试将CollectionDataContractAttribute
用于集合定义,DataMemberAttribute
用于MySpecialProperty
,但它会在 System.Runtime.Serialization.dll中导致System.Runtime.Serialization.InvalidDataContractException
异常。是否有其他方法可以获得上述XML结果?