0

我实现了一个扩展方法List<T>。在那个扩展方法中,有一个谓词我无法表达我想要谓词做什么。我制定了一套测试来阐述我的意图。 IsAssignableFrom不知何故无法识别接口或子类 - 或者(更有可能)我用错了。该测试ShouldRemove_All不会删除任何内容。该测试ShouldRemove_RA_AND_RAA仅删除 RA。第三次测试通过。

这是代码 - 我需要如何调整扩展方法才能通过所有测试?

代码确实可以编译并且可以执行——它所需要的只是一个带有 NUnit 的项目。

using System;
using System.Collections.Generic;
using NUnit.Framework;
using System.Text;

namespace SystemTools
{

    public static class ListExtension
    {
        public static int RemoveAllOfType<T>(this List<T> list, Type removeable)
        {
            Predicate<T> match = (x) =>
            {
                return x.GetType().IsAssignableFrom(removeable);
            };
            return list.RemoveAll(match);
        }
    }

    [TestFixture]
    class ListExtension_Test
    {
        private interface IRoot { }
        private class Child_RA : IRoot { }
        private class Child_RB : IRoot { }
        private class Child_RAA : Child_RA { }

        List<IRoot> scenario;
        int sumofelements, RA, RB, RAA;

        private String DebugString(List<IRoot> list)
        {
            StringBuilder ret = new StringBuilder(list.Count * 10);
            ret.Append("Remaining: '");
            Boolean atleastone = false;
            foreach (var item in list)
            {
                if (atleastone) ret.Append(", ");
                ret.Append(item.GetType().Name);
                atleastone = true;
            }
            ret.Append("'");
            return ret.ToString();
        }

        [SetUp]
        public void SetUp()
        {
            RB = 1; RA = 2; RAA = 3;
            sumofelements = RB + RA + RAA;
            scenario = new List<IRoot>();
            for (int i = 1; i <= RB; i++) scenario.Add(new Child_RB());
            for (int i = 1; i <= RA; i++) scenario.Add(new Child_RA());
            for (int i = 1; i <= RAA; i++) scenario.Add(new Child_RAA());
        }

        [Test]
        public void ShouldRemove_All()
        {
            scenario.RemoveAllOfType(typeof(IRoot));
            int remaining = 0;
            Assert.AreEqual(remaining, scenario.Count, DebugString(scenario));
        }

        [Test]
        public void ShouldRemove_RB()
        {
            scenario.RemoveAllOfType(typeof(Child_RB));
            int remaining = sumofelements - RB;
            Assert.AreEqual(remaining, scenario.Count, DebugString(scenario));
        }

        [Test]
        public void ShouldRemove_RA_AND_RAA()
        {
            scenario.RemoveAllOfType(typeof(Child_RA));
            int remaining = sumofelements - (RA + RAA);
            Assert.AreEqual(remaining, scenario.Count, DebugString(scenario));
        }
    }
}
4

1 回答 1

0
return removeable.IsAssignableFrom(x.GetType());
于 2012-06-13T08:49:03.480 回答