问题
I just updated to r275 version and it doesn't seem to manage correctly DataContract classes any more By serializing this very simple class:
[DataContract]
public class ProtoData
{
[DataMember(Order = 1)]
private long _id;
[DataMember(Order = 2)]
private string _firstName;
[DataMember(Order = 3)]
private string _lastName;
public long Id
{
get { return _id; }
set { _id = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public ProtoData(long id, string firstName, string lastName)
{
_id = id;
_firstName = firstName;
_lastName = lastName;
}
public ProtoData()
{
}
I get Only data-contract classes (and lists/arrays of such) can be processed (error processing ProtoData)
回答1:
Really? that is.... odd; I would have expected the unit tests to spt such a breaking change. Are you sure you are using the right version? There is a 2.0 version (which doesn't include [DataContract]
support, since this is in WCF, a 3.0 extension) and a separate 3.0 version. You want the 3.0 version (NET30.zip
).
Tested successfully with r275/NET30:
static void Main() {
ProtoData pd = new ProtoData {
FirstName = "Marc",
LastName = "Gravell",
Id = 23354
}, clone;
using (MemoryStream ms = new MemoryStream()) {
Serializer.Serialize(ms, pd);
Console.WriteLine(ms.Length);
ms.Position = 0;
clone = Serializer.Deserialize<ProtoData>(ms);
}
Console.WriteLine(clone.FirstName);
Console.WriteLine(clone.LastName);
Console.WriteLine(clone.Id);
}
With output:
19
Marc
Gravell
23354
回答2:
Try the following:
- Remove all private members
Use public properties
public string LastName;
Mark all public properties with [DataMember]
来源:https://stackoverflow.com/questions/1775082/datacontract-serialization-with-protobuf-net-r275