为什么NUnit的Assert.That(..)有ref重载?

时间:2011-02-11 10:04:22

标签: c# nunit

也许我只是愚蠢但是你何时以及为什么要使用:

NUnit.Framework.Assert.That<T>(ref T, NUnit.Framework.Constraints.IResolveConstraint, string, params object[])
NUnit.Framework.Assert.That<T>(ref T, NUnit.Framework.Constraints.IResolveConstraint, string)
NUnit.Framework.Assert.That<T>(ref T, NUnit.Framework.Constraints.IResolveConstraint)

取代:

NUnit.Framework.Assert.That(object, NUnit.Framework.Constraints.IResolveConstraint, string, params object[])
NUnit.Framework.Assert.That(object, NUnit.Framework.Constraints.IResolveConstraint, string)
NUnit.Framework.Assert.That(object, NUnit.Framework.Constraints.IResolveConstraint)

通过ref传递给这些方法有什么好处?

1 个答案:

答案 0 :(得分:5)

深入研究NUnit源代码,我发现了这个:

static public void That<T>(ref T actual, IResolveConstraint expression, string message, params object[] args)
{
    Constraint constraint = expression.Resolve();

    Assert.IncrementAssertCount();
    if (!constraint.Matches(ref actual))
    {
        MessageWriter writer = new TextMessageWriter(message, args);
        constraint.WriteMessageTo(writer);
        throw new AssertionException(writer.ToString());
    }
}

    public virtual bool Matches<T>(ref T actual)
    {
        return Matches(actual);
    }

    static public void That(object actual, IResolveConstraint expression, string message, params object[] args)
    {
        Constraint constraint = expression.Resolve();

        Assert.IncrementAssertCount();
        if (!constraint.Matches(actual))
        {
            MessageWriter writer = new TextMessageWriter(message, args);
            constraint.WriteMessageTo(writer);
            throw new AssertionException(writer.ToString());
        }
    }

如您所见,实施方案没有区别。 Ref T actual重载允许您将值类型作为引用传递,而引用类型已作为引用传递。