2014-08-31 55 views
1

我想格式化短語,並根據項目的數量做結尾。c#內嵌切換格式字符串

string s = string.Format("There are {0} items, bla bla {1}", 
itemsCnt, 
() => {switch(itemsCnt) 
{ 
    case 0: 
     return "make some..."; 
    case 1: 
    case 2: 
     return "try more"; 
    default: 
     return "enough"; 
}} 
); 

的語法是不正確的,我相信匿名方法應該在這裏莫名其妙地工作...

更新

我可以使用單獨的格式化功能。我想在Razor中使用這個函數,我希望看到在一個地方合成邏輯。進而我很好奇,怎麼辦呢:-)

+3

似乎是在做一個過於複雜的方式它。爲什麼不在你的賦值/格式化語句之前用switch語句調用它來計算「結尾」? – RenniePet 2014-08-31 11:33:23

+0

string.Format沒有佔用並執行Func對象的重載。它只是調用params數組中對象的ToString()方法,這對於Func對象通常沒有多大意義。 – chris 2014-08-31 11:40:00

回答

3

的代碼創建函數求委託並執行:

string s = string.Format("There are {0} items, bla bla {1}", 
      itemsCnt, 
      new Func<string>(() => 
      { 
       switch (itemsCnt) 
       { 
        case 0: 
         return "make some..."; 
        case 1: 
        case 2: 
         return "try more"; 
        default: 
         return "enough"; 
       } 
      })() 
      ); 
+0

就是這樣。我喜歡這個解決方案不僅僅是單獨的功能,因爲它很容易在Razor中使用,格式化邏輯也在一個地方。 – qub1n 2014-08-31 11:42:50

+2

@ qub1n你需要儘可能少的代碼在你的意見。在這種情況下,方法的方法聽起來更爲合理,您可以將該方法粘貼到視圖模型中。 – CodeCaster 2014-08-31 11:50:22

4

爲什麼在這裏使用匿名方法?

定期會做精細:

private string Translate(int itemsCnt) 
{ 
switch(itemsCnt) 
{ 
    case 0: 
     return "make some..."; 
    case 1: 
    case 2: 
     return "try more"; 
    default: 
     return "enough"; 
} 
} 

那麼結果是:

string s = string.Format("There are {0} items, bla bla {1}", 
         itemsCnt, 
         Translate(itemsCnt)); 

string.Format(...)has no overload稱取功能