【问题标题】:C# compare lists List<T>C# 比较列表 List<T>
【发布时间】:2017-02-01 19:46:01
【问题描述】:

使用 Microsoft.VisualStudio.TestTools.UnitTesting;

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

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));
    }
}

但是如果 Values(和函数的返回值)是

List<int>

当然,它不起作用。所以,我发现不是我需要的

CollectionAssert.AreEqual

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

【问题讨论】:

  • 我知道。但我收到错误“无法从 TValue 转换为 System.Collections.ICollection”。我想我不得不说 TValue 可以是 System.Collections.ICollection

标签: c# list unit-testing collections assert


【解决方案1】:

您需要将值转换为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));
         }
    }
}

【讨论】:

  • 这行得通,谢谢!除了我需要指定 System.Collections.ICollection 而不是 ICollection
  • 很高兴知道 :) 您也可以在测试类中添加 using System.Collections; 语句。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多