0

我试图编写一段代码,用于将字符串列表转换为整数列表,我从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 个项目。

我在填充它之前尝试newing并在方法中将值添加到和ing 列表中。但是容量还是一样的。我不想手动设置容量,因为此方法不会用于已确定容量的列表。actuallist.Add()expectednewConvertListOfStringToListOfInt

我该怎么做才能通过这个测试?为什么容量不一样?列表的容量是如何确定的,它们依赖于什么?

这是 .NET Framework 4.0。

4

3 回答 3

2

a的容量List<T>默认为4。如果一项一项添加,则每次添加超过当前容量的元素时,它将翻倍。

http://msdn.microsoft.com/en-us/library/y52x03h2.aspx

在我看来,你不应该担心这种情况下的容量。要使您的单元测试通过,您可以更改列表的初始化:

List<int> expected = new List<int>(3) { 1, 2, 3};

由于ConvertAll方法中的优化将占用旧容量。

一个提示:

如果您不关心优化每一点性能,您可以通过以下方式替换此方法

listOfStr.Select(s => int.Parse(s)).ToList();

只是为了让它更易于维护。

于 2012-06-28T13:10:01.760 回答
2

试试这个:

Assert.IsTrue(actual.SequenceEqual(expected));

原因是列表是复杂的对象,列表的相等性不是由每个元素相同来确定的,而是定义为它们指向同一个列表。序列相等方法为您迭代列表并确定项目级别的相等性。

如果列表中的项目是复杂类型,那么它将使用这些项目的默认相等比较器。

于 2012-06-28T13:19:44.080 回答
1

你有没有尝试过:

Assert.IsTrue(expected.SequenceEqual<int>(actual));
于 2012-06-28T13:19:08.110 回答