に拡張メソッドを実装しましたList<T>
。その拡張方法には、述語に何をさせたいかを表現できない述語があります。私は自分の意図を詳しく説明するために一連のテストを作成しました。
IsAssignableFrom
どういうわけかインターフェイスや子クラスを識別しません-または(より可能性が高い)私はそれを間違って使用しています。テストShouldRemove_All
は何も削除しません。テストShouldRemove_RA_AND_RAA
はRAのみを削除します。3番目のテストに合格します。
コードは次のとおりです。すべてのテストに合格するには、拡張メソッドをどのように適応させる必要がありますか?
コードはコンパイルされ、実行できます。必要なのは、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));
}
}
}