2014-02-06 90 views
0

我想知道是否有可能將此while循環轉換爲lambda表達式?我知道這是可能的,如果它是一個對或foreach循環,但在循環這是一個正常的,平淡的道:我可以把它變成lambda表達式嗎?

while (path.Substring(path.Length - 4) != ".txt" || path.Substring(path.Length - 4) != ".xml") 
{ 
    Console.WriteLine("File not a .txt or .xml extension! Enter the file name:"); 
    path = Console.ReadLine(); 
} 

如果可能的話,怎麼會一個改變這個循環到這樣一個lambda聲明?

+1

你爲什麼要這麼做? – Max

+1

而且,爲什麼這是一個while循環開始?它看起來像一個非常簡單的if語句。 –

+3

你可以把任何語句變成lambda:'new Action(()=> {while(...){...}})();'。這完全沒用,但你似乎並沒有要求*有用的東西。你能詳細說明嗎? – hvd

回答

0

如果你想學習和學術的目的這樣做:

Func<string[], string> getFile = (validExtensions) => 
    { 
     string path = ""; 
     while (!validExtensions.Contains(Path.GetExtension(path))) 
     { 
      Console.WriteLine("File not a .txt or .xml extension! Enter the file name:"); 
      path = Console.ReadLine(); 
     } 
     return path; 
    }; 

    string path = getFile.Invoke(new string[]{ ".txt", ".xml" }); 

使用.Invoke(string[])調用它,傳遞所需的文件擴展名。

通過它進入的方法,例如:

public string UseFunc(Func<string[], string> getFile, string[] validExtensions) 
{ 
    return getFile.Invoke(validExtensions); 
} 

string path = foo.UseFunc(getFile); 
+2

這不會編譯。即使你把它改成了可以編譯的東西,它也是沒用的,這就是爲什麼我把類似的問題作爲對問題的評論,而不是回答。 – hvd

+0

@ hvd,修正,謝謝。 –

+0

如果您將其保存在匿名方法的本地變量中,您將如何處理用戶輸入的路徑? – hvd

2

鑑於對這個問題的評論認爲,這是不是真正的lambda表達式,而是最大限度地減少代碼,這裏有一些小的建議,以避免一些重複代碼:

string[] validExtensions = { ".txt", ".xml" }; 
do 
{ 
    Console.WriteLine("Enter the file name:"); 
    path = Console.ReadLine(); 
    if (!validExtensions.Contains(Path.GetExtension(path))) 
    { 
     Console.Write("File not a .txt or .xml extension! "); 
     path = null; 
    } 
} 
while (path == null); 

檢查另一部分僅需要添加擴展到陣列,它不需要複製代碼,以確定所述延伸。字符串"Enter the file name:"只需出現一次,即使您希望爲第一個提示輸入稍微不同的消息。讀取一行的代碼也只需要出現一次。

就個人而言,我認爲你所擁有的重複是如此之小以至於沒有必要避免它,但是如果你需要允許三個擴展名或者從一些其他單個函數調用不足的地方。

一些補充意見:

  • Console.ReadLine()可以返回null。就像你的問題中的代碼一樣,這個版本沒有正確處理。
  • 通常會忽略文件擴展名中的情況。你真的想拒絕".TXT"作爲文件擴展名嗎?
  • 您的while條件path.Substring(path.Length - 4) != ".txt" || path.Substring(path.Length - 4) != ".xml"永遠不會是錯誤的。它可能是真的,或者它可能會拋出異常,但循環永遠不會正常終止。
相關問題