2

平等比较如何为 a 工作Func?我已将问题的复杂性降低到这些单元测试:

[Test]
public void Will_Pass()
{
    Func<string> func = () => "key";
    Assert.That(func, Is.EqualTo(func));
}

[Test]
public void Will_Fail()
{
    Func<string> funcA = () => "key";
    Func<string> funcB = () => "key";
    Assert.That(funcA, Is.EqualTo(funcB));
}

我需要测试 - 并成功断言 - a 的一个实例Func等于另一个实例。所以我基本上需要一种方法来让 Failing 测试通过。

有没有办法在不创建自定义类型和覆盖的情况下做到这一点Equals()

4

1 回答 1

4

Your failing test shouldn't pass. They're not equal functions as far as anything in .NET is concerned - at least with the current Microsoft C# compiler implementation. The delegates will refer to separate generated methods (easily verified by looking at the IL.) The language specification allows them to be equal, but doesn't require it, and I don't know of any implementation that would do this.

Equality comparison for delegates basically consists of (for a single-action delegate):

  • Do the delegates refer to the same method?
  • If the delegates have targets, are those targets equal?

The first condition will be false in your test.

于 2012-10-08T09:17:34.037 回答