2012-06-13 27 views
0

我實現了一個擴展方法爲List<T>。在那個擴展方法中,有一個謂詞我無法表達我想要謂詞做什麼。我制定了一套測試來闡述我的意圖。 IsAssignableFrom以某種方式不確定接口和子類 - 或者(更可能)我錯誤地使用它。測試ShouldRemove_All不會刪除任何東西。測試ShouldRemove_RA_AND_RAA僅刪除RA。第三次測試通過。使用通過IsAssignableFrom標識的RemoveAll謂詞

以下是代碼 - 我如何修改擴展方法以通過所有測試?

該代碼確實可以編譯並且可以執行 - 它只需要一個帶有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

我只是解決了它 '返回removeable.IsAssignableFrom(x.GetType());'是如何應該的。 – Johannes

回答

0
return removeable.IsAssignableFrom(x.GetType());