4

我正在尝试使用以下代码使用 protobuf-net 使用 EventHandler 序列化一个类:

    [ProtoContract]
    class Thing
    {
        [ProtoMember(5, AsReference = true)]
        public EventHandler _DoSomething;

        public event EventHandler DoSomething
        {
            add { _DoSomething += value; }
            remove { _DoSomething -= value; }
        }

        public void PerformSomething(object sender, EventArgs args)
        {
        }
    }

    [TestMethod]
    public void SerializingAClassWithAnEvent_Deserializes()
    {
        var Guy1 = new Thing() {};
        var Guy2 = new Thing() {};
        Guy2.DoSomething += Guy1.PerformSomething;
        Assert.IsNotNull(Guy2._DoSomething);

        MemoryStream buffer = new MemoryStream();
        Serializer.Serialize(buffer, Guy2);
        MemoryStream afterStream = new MemoryStream(buffer.ToArray());
        var outGuy = Serializer.Deserialize<Thing>(afterStream);

        Assert.IsNotNull(outGuy._DoSomething);
    }

此代码编译并运行良好,但第二个断言失败,因为 _DoSomething EventHandler 仍然为空。我错过了什么?

4

1 回答 1

4

这里的文档中不支持 EventHandlers

custom classes that:
   are marked as data-contract;
   have a parameterless constructor;
   for Silverlight: are public
many common primitives etc
single dimension arrays: T[]
List<T> / IList<T>
Dictionary<TKey,TValue> / IDictionary<TKey,TValue>
any type which implements IEnumerable<T> and has an Add(T) method
于 2013-01-03T22:13:07.663 回答