OnDeserialized attribute for ProtoBuf-NET

谁都会走 提交于 2019-12-10 23:26:29

问题


We used JSON.NET to serialize our data together with OnDeserialized attribute to execute custom code after deserialization:

[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context)
{
    ...
}

Now we try to use protobuf instead of JSON.NET and this method is not executing. Is there another way to achieve this behaviour with protobuf.net?

Here is an example that doesn't work:

class Program
{
    static void Main(string[] args)
    {
        RuntimeTypeModel.Default.Add(typeof (Profile), false).Add(1000, "Id").Add(1001, "Text");

        var test = new Profile {Id = Guid.NewGuid(), Text = "123"};

        using (var memoryStream = new MemoryStream())
        {
            Serializer.Serialize(memoryStream, test);

            memoryStream.Seek(0, SeekOrigin.Begin);

            var deserialized =  Serializer.Deserialize<Profile>(memoryStream);

            Console.WriteLine(deserialized.Text); // should output "changed"
            Console.ReadLine();
        }
    }
}

[ProtoContract]
public class Profile
{
    public Guid Id { get; set; }
    public string Text { get; set; }

    [OnDeserialized]
    internal void OnDeserializedMethod(StreamingContext context)
    {
        Text = "changed";
    }
}

回答1:


Works fine for me:

[ProtoContract]
public class Foo
{
    [OnDeserialized]
    internal void OnDeserializedMethod(StreamingContext context)
    {
        Console.WriteLine("OnDeserializedMethod");
    }

    [ProtoMember(1)]
    public string Bar { get;set; }

    static void Main()
    {
        var foo = new Foo { Bar = "abc" };
        var clone = Serializer.DeepClone(foo);
        Console.WriteLine(clone.Bar);
    }
}

Output:

OnDeserializedMethod
abc

Can you be more specific? Perhaps showing a complete example that reproduces what you are seeing? Also: are you sure you are using protobuf-net? Some people get very confused between protobuf-net and protobuf-csharp-port. I cannot comment on what features the latter supports.



来源:https://stackoverflow.com/questions/21855199/ondeserialized-attribute-for-protobuf-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!