在收集递归断言 [英] recursive assert on collection

查看:116
本文介绍了在收集递归断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样一个测试:

[Test]
    public void TestCollectionAssert ()
    {
        var a1 = new [] { new [] { "a" } };
        var a2 = new [] { new [] { "a" } };

        Assert.AreNotEqual (a1, a2);
        //CollectionAssert.AreEqual (a1, a2);
        CollectionAssert.AreEquivalent (a1, a2);
    }

通过。 我真正的情况是比较复杂的,但解决这个在一个通用的方法就可以了。 任何想法?

to pass. My real case is more complicated, but solving this one in a generic way will do. Any ideas?

推荐答案

有一个有用的LINQ运营商所谓的 SequenceEqual() 用于比较两个序列是否相等。 SequenceEqual()遍历任何两个的IEnumerable&其中;> 序列,并验证它们具有相同的元素数和同一索引处元素相等(使用默认的相等比较器)。但是,既然你有嵌套的收藏,您需要延长平等的概念适用于他们。幸运的是,过载,允许你提供自己的的IEqualityComparer<> 对象。

There's a useful LINQ operator called SequenceEqual() which compares two sequences for equality. SequenceEqual() walks through any two IEnumerable<> sequences and verifies that they have the same number of elements and that elements at the same index are equal (using the default equality comparer). However, since you have nested collections, you need to extend the concept of equality to apply to them as well. Fortunately, there's an overload that allows you supply your own IEqualityComparer<> object.

由于它是尴尬不断有定义一个类来提供平等的语义,我写了一个通用的扩展,使您可以使用委托来代替。让我们来看看code:

Since it's awkward to constantly have to define a class to provide equality semantics, I've written a generic extension that allows you to use a delegate instead. Let's look at the code:

public static class ComparerExt
{
    private class GenericComparer<T> : IEqualityComparer<T>
    {
        private readonly Func<T, T, bool> m_EqualityFunc;

        public GenericComparer( Func<T,T,bool> compareFunc )
        {
            m_EqualityFunc = compareFunc;
        }

        public bool Equals(T x, T y)
        {
            return m_EqualityFunc(x, y);
        }
    }

    // converts a delegate into an IComparer
    public static IEqualityComparer<T> AreEqual<T>( Func<T,T,bool> compareFunc )
    {
        compareFunc.ThrowIfNull("compareFunc");

        return new GenericComparer<T>(compareFunc);
    }
}

现在,我们可以比较两个序列很轻松地:

Assert.IsTrue( 
   // check that outer sequences are equivalent...
   a1.SequenceEqual( a2,
                     // define equality as inner sequences being equal... 
                     ComparerExt.AreEqual( (a,b) => a.SequenceEqual(b) ) );

这篇关于在收集递归断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆