我为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));
}
}
}
答案 0 :(得分:0)
return removeable.IsAssignableFrom(x.GetType());