开发者

DataContract serialization with protobuf-net r275

开发者 https://www.devze.com 2022-12-12 06:44 出处:网络
I just updated to r275 version and it doesn\'t seem to manage correctly DataContract classes any more

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/开发者_Go百科arrays of such) can be processed (error processing ProtoData)


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


Try the following:

  • Remove all private members
  • Use public properties

    public string LastName;

  • Mark all public properties with [DataMember]

0

精彩评论

暂无评论...
验证码 换一张
取 消