C#比较列表列表<;T>;

C#比较列表列表<;T>;,c#,list,unit-testing,collections,assert,C#,List,Unit Testing,Collections,Assert,使用Microsoft.VisualStudio.TestTools.UnitTesting 我想要通用测试方法,它获取字典和函数,然后检查每个字典条目在值和函数(键)之间的相等性: 对于这种情况。 但现在我不得不说,我的价值观是System.Collections.ICollection。如何执行此操作?您需要将值强制转换为ICollection,这样编译器就不会抱怨了 public void TestMethod<TKey, TValue>(Dictionary<TKey,

使用Microsoft.VisualStudio.TestTools.UnitTesting

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

对于这种情况。
但现在我不得不说,我的价值观是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));
         }
    }
}
public void测试方法(Dictionary dict,Func-Func)
{
foreach(dict中的var测试)
{
如果(test.Value为ICollection)
{
CollectionAssert.AreEqual((ICollection)test.Value,(ICollection)func(test.Key));
}
其他的
{
AreEqual(test.Value,func(test.Key));
}
}
}

我知道。但我得到一个错误“无法从TValue转换到System.Collections.ICollection”。我想我不得不说,TValue可以是System.Collections.ICollection这很有效,谢谢!除了我需要指定System.Collections.ICollection而不是ICollectionGood to know:)之外,您可以使用System.Collections添加
语句也添加到测试类中。
List<int>
CollectionAssert.AreEqual
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));
         }
    }
}