2017-05-03 82 views
0

所以,我有兩種方法:我有兩個功能只有一些條件不同。它可以統一嗎?

public static string Figure2D() 
    { 
     dynamic shapeValue; 
     do 
     { 
      shapeValue = Presentation.Present(); 
     } 
     while (shapeValue.Is3D); 
     return shapeValue.ToString("R"); 
    } 

    public static string Figure3D() 
    { 
     dynamic shapeValue; 
     do 
     { 
      shapeValue = Presentation.Present(); 
     } 
     while (!shapeValue.Is3D); 
     return shapeValue.ToString("R"); 
    } 

它們之間唯一的區別是while條件。我怎樣才能將這兩個功能合併成一個功能?傳遞參數值可能需要&,但我確實希望保持簡短。有任何想法嗎?

+0

如何@stuartd出現了一個'!'在一個 – degant

+0

@stuartd一個被否定,另一種是不。 – Bytewave

+0

小文本再次獲勝,對不起 – stuartd

回答

4

public static string Figure(Predicate<dynamic> p) 
    { 
     dynamic shapeValue; 
     do 
     { 
      shapeValue = Presentation.Present(); 
     } 
     while (p(shapeValue)); 
     return shapeValue.ToString("R"); 
    } 
+2

我建議'Func '而不是'Predicate',所以它可以簡單地用作'figure(thing =>!thing.Is3D)' – quetzalcoatl

+0

嗯,什麼是Predicate ,我將如何通過這個條件? (對不起,有點新C#) – Jesper

+1

@Jesper:它是一個委託,返回一個布爾(而不是Func,它返回任何你指定的)。基本上,Predicate === Func <..., bool> ..欲瞭解更多信息,請查看VS中的MSDN或intellisense。 – quetzalcoatl

相關問題