Cannot serialize this List<T> extension
I'm trying to push a subset of a collection of data through WCF to be consumed by WCF - think paged data. As such, I want this collection to have one page's worth of data as well as a total number of results. I figured this should be trivial by creating a custom object that extends List. However, everything I do results in my TotalNumber property coming across as 0. All of the data gets serialized/deserialized just fine but that single integer won't come across at all.
Here's my first attempt that failed:
[Serializable]
public class PartialList<T> : List<T>
{
public PartialList()
{
}
public PartialList(IEnumerable<T> collection)
: base(collection)
{
}
[DataMember]
public int UnpartialTotalCount { get; set; }
And here's my second attempt that failed in the exact same way:
[Serializable]
public class P开发者_运维知识库artialList<T> : List<T>, ISerializable
{
public PartialList()
{
}
public PartialList(IEnumerable<T> collection)
: base(collection)
{
}
[DataMember]
public int UnpartialTotalCount { get; set; }
protected PartialList(SerializationInfo info, StreamingContext context)
{
UnpartialTotalCount = info.GetInt32("UnpartialTotalCount");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("UnpartialTotalCount", UnpartialTotalCount);
}
}
What's the deal here??
Just if anyone else finds this topic, <DataContract>
is not valid for custom collection types.
You should use <CollectionDataContract>
instead. It´s a similar namespace, with equivalent members, but it is able to deal with custom lists and dictionaries. For more info, see "Customizing collections" in this article:
http://msdn.microsoft.com/en-us/library/aa347850.aspx
For WCF, you probably want to use the [DataContract]
attribute on the class, rather than the ISerializable interface. WCF uses a different type of serialization, and a different convention for marking classes and members that should be serialized.
WCF may support [Serializable] or ISerializable, but I would recommend using just the [DataContract]/[DataMember]/etc. convention for WCF.
According to this question, this is "By Design". :-(
精彩评论