我试图编写一段代码,用于将字符串列表转换为整数列表,我从ConvertAllList<int> list = listOfStr.ConvertAll<int>(delegate(string s) { return ConvertStringToInt(s); });
得到了这一行。
public static List<int> ConvertListOfStringToListOfInt(List<string> listOfStr)
{
List<int> list = listOfStr.ConvertAll<int>(delegate(string s) { return ConvertStringToInt(s); });
return list;
}
/// <summary>
/// converts the given str to integer
/// </summary>
/// <param name="str">string to be converted</param>
/// <returns>returns the int value of the given string</returns>
public static int ConvertStringToInt(string str)
{
int convertedValue = int.Parse(str);
//(int.TryParse(str, out convertedValue))
return convertedValue;
}
除了一件事,代码运行良好。
我为上述方法创建了单元测试,TestMethod
如下
/// <summary>
///A test for ConvertListOfStringToListOfInt
///</summary>
[TestMethod()]
public void ConvertListOfStringToListOfIntTest()
{
List<string> listOfStr = new List<string> { "1", "2", "3"}; // TODO: Initialize to an appropriate value
List<int> expected = new List<int> { 1, 2, 3}; // TODO: Initialize to an appropriate value
List<int> actual;
actual = Conversions.ConvertListOfStringToListOfInt(listOfStr);
Assert.AreEqual(expected, actual);
//Assert.Inconclusive("Verify the correctness of this test method.");
}
我在传递方法和预期列表的列表中给出了相同的值,只是类型不同(预期是整数列表,传递的列表是字符串列表)。我运行测试并收到此错误消息:
Assert.AreEqual failed. Expected:<System.Collections.Generic.List`1[System.Int32]>. Actual:<System.Collections.Generic.List`1[System.Int32]>.
好吧,类型实际上是相等的,所以我认为列表中可能有一些不同的东西,我对其进行了调试。
结果listOfStr.Capacity
是 4 并且在它的 items 成员中有 null 项目作为 [3] 项目,因为 items 成员中的相同位置预期有 0 并且expected.Capacity
也是 4。
但是,actual.Capacity
是 3,它的 items 成员中确实有 3 个项目。
我在填充它之前尝试new
ing并在方法中将值添加到和ing 列表中。但是容量还是一样的。我不想手动设置容量,因为此方法不会用于已确定容量的列表。actual
list.Add()
expected
new
ConvertListOfStringToListOfInt
我该怎么做才能通过这个测试?为什么容量不一样?列表的容量是如何确定的,它们依赖于什么?
这是 .NET Framework 4.0。