c# compare the data in two object models

前端 未结 3 1288
终归单人心
终归单人心 2021-01-12 02:15

I have a dialog, when spawned it gets populated with the data in an object model. At this point the data is copied and stored in a \"backup\" object model. When the user h

3条回答
  •  半阙折子戏
    2021-01-12 02:31

    I didn't bother with a hash string but just a straight Binary serialisation works wonders. When the dialog opens serialise the object model.

    BinaryFormatter formatter = new BinaryFormatter();
    m_backupStream = new MemoryStream();
    formatter.Serialize(m_backupStream,m_objectModel);
    

    Then if the user adds to the object model using available controls (or not). When the dialog closes you can compare to the original serialisation with a new one - this for me is how i decide whether or not an Undo state is required.

    BinaryFormatter formatter = new BinaryFormatter();
    MemoryStream liveStream = new MemoryStream();
    formatter.Serialize(liveStream,m_objectModel);
    byte[] streamOneBytes = liveStream.ToArray();
    byte[] streamTwoBytes = m_backupStream.ToArray();
    if(!CompareArrays(streamOneBytes, streamTwoBytes))
        AddUndoState();
    

    And the compare arrays function incase anybody needs it - prob not the best way of comparing two arrays im sure.

    private bool CompareArrays(byte[] a, byte[] b)
    {
        if (a.Length != b.Length)
           return false;
    
        for (int i = 0; i < a.Length;i++)
        {
           if (a[i] != b[i])
            return false;
        }
        return true;
    }
    

提交回复
热议问题