1

我在将队列保存到文件时遇到问题,然后将其加载到新队列中,然后将旧队列与新队列进行比较。

我有一个简单的TestMessageClass,现在我想序列化队列并将其保存到一个名为test.bin 的文件中。我认为工作正常,但是当我将队列加载到另一个变量并比较它们时,它给了我以下错误:

Expected: equivalent to 

Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass


But was:


Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass, 
Grid.NodeTests.MessageSink_Tests.MessageSinkTests+TestMessageClass

如果我将普通字符串排入队列,它一切正常,但如果我使用我的 TestMessageClass 它将不再工作。

[Serializable()]
class TestMessageClass
{
    public enum MessageType
    { 
        Broadcast,
        Unicast
    }
}

internal interface ISerializationService
{
      void Serialize(Stream outputStream, object obj);
      T Deserialize<T>(Stream inputStream);
}

public void Serialize(Stream outputStream, Object obj)
{

    IFormatter serializer = new BinaryFormatter();
    serializer.Serialize(outputStream, obj);


}

public T Deserialize<T>(Stream inputStream)
{

    var result = new BinaryFormatter().Deserialize(inputStream);

    return (T)result;

}
[Test]
public void CompareQueue()
{
    Queue queue1 = new Queue();

    var message = new TestMessageClass();

    for (int i = 0; i < 100; i++)
        queue1.Enqueue(message);

    ISerializationService service = new SerializationService();

    FileStream stream = File.Open("Test.bin" , FileMode.Create , FileAccess.Write);

    service.Serialize(stream, queue1);
    stream.Close();

    FileStream stream2 = File.Open("Test.bin" , FileMode.Open ,FileAccess.Read);

    Queue queue2 = service.Deserialize<Queue>(stream2);
    stream2.Close();
    CollectionAssert.AreEquivalent(queue1,queue2);

}
4

1 回答 1

2

最简单的解决方案是在您的 TestMessageClass 上实现 Equals 以确定 2 个不同的实例是否相等。通常,您可以通过比较每个实例上的所有属性来实现该方法。

当您对其进行序列化然后反序列化时,它将创建新实例,因此默认的 Equals 实现将返回 false,因为它只是比较实例是否相同。

于 2013-05-23T10:59:45.497 回答