C# 比较列表 List<T>

C# compare lists List<T>

使用Microsoft.VisualStudio.TestTools.UnitTesting;

我想要通用测试方法,它获取字典和函数,然后检查值和函数(键)之间的每个字典条目是否相等:

public void TestMethod<TKey, TValue>(Dictionary<TKey, TValue> dict, Func<TKey, TValue> func)
{
    foreach (var test in dict)
    {
         Assert.AreEqual(test.Value, func(test.Key));
    }
}

但是如果值(和 return 函数的值)是

List<int>

当然不行。所以,我发现比我需要的

CollectionAssert.AreEqual

对于这种情况。 但是现在我不得不说,我的价值是System.Collections.ICollection。如何做到这一点?

您需要将值转换为 ICollection 这样编译器就不会报错。

public void TestMethod<TKey, TValue>(Dictionary<TKey, TValue> dict, Func<TKey, TValue> func)
{
    foreach (var test in dict)
    {
         if (test.Value is ICollection)
         {
              CollectionAssert.AreEqual((ICollection)test.Value, (ICollection)func(test.Key));
         }
         else
         {
              Assert.AreEqual(test.Value, func(test.Key));
         }
    }
}