首页 > 解决方案 > How to compare a two Cursor objects?

问题描述

I am creating an unit test and I have a Cursor that should be made from a specific Bitmap. The Cursor is created using the following code:

cursor = new Cursor(bmp.GetHicon());

where bmp is a Bitmap.

This always maked the test fail (the handle created by bmp.GetHicon() is always new):

Assert.AreEqual(bmp.GetHicon(), cursor.Handle);

I also thought of using Icon.FromHandle.

标签: c#winformsunit-testingbitmap

解决方案


事实上,您正在寻找如何比较两个游标。

你有位图,你有一个光标,你想检查光标是否是使用位图创建的。为此,作为一种选择,从位图创建一个游标,然后进行比较,将这两个游标(从位图创建的新游标和现有游标)保存到流中并比较流。

例如:

bool ArEqual(Cursor cur1, Cursor cur2)
{
    byte[] bytes1, bytes2;
    using (var ico = Icon.FromHandle(cur1.Handle))
    using (var fs = new MemoryStream())
    {
        ico.Save(fs);
        bytes1 = fs.ToArray();
    }
    using (var ico = Icon.FromHandle(cur2.Handle))
    using (var fs = new MemoryStream())
    {
        ico.Save(fs);
        bytes2 = fs.ToArray();
    }
    return bytes1.SequenceEqual(bytes2);
}

推荐阅读