2016-06-14 24 views
1

我正在使用LINQ查詢解析輸入字符串到類。我已將查詢包裝在try/catch塊中以處理分析錯誤。問題在於,在我期望它發生的地方沒有捕獲到異常,它只會在訪問結果對象(parsedList)時停止程序流。我誤解了關於LINQ如何工作或異常情況如何工作的內容?從預期的LINQ查詢異常未捕獲

public class Foo 
{ 
    public decimal Price { get; set; } 
    public decimal VAT { get; set; } 
} 

public class MyClient 
{ 
    public IEnumerable<Foo> ParseStringToList(string inputString) 
    { 
     IEnumerable<Foo> parsedList = null; 
     try 
     { 
      string[] lines = inputString.Split(new string[] { "\n" }, StringSplitOptions.None); 

      // Exception should be generated here 
      parsedList = 
       from line in lines 
       let fields = line.Split('\t') 
       where fields.Length > 1 
       select new Foo() 
       { 
        Price = Decimal.Parse(fields[0], CultureInfo.InvariantCulture), //0.00 
        VAT = Decimal.Parse(fields[1], CultureInfo.InvariantCulture) //NotADecimal (EXCEPTION EXPECTED) 
       }; 
     } 
     catch (FormatException) 
     { 
      Console.WriteLine("It's what we expected!"); 
     } 

     Console.WriteLine("Huh, no error."); 
     return parsedList; 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     MyClient client = new MyClient(); 
     string inputString = "0.00\tNotADecimal\n"; 
     IEnumerable<Foo> parsedList = client.ParseStringToList(inputString); 
     try 
     { 
      //Exception only generated here 
      Console.WriteLine(parsedList.First<Foo>().Price.ToString()); 
     } 
     catch (FormatException) 
     { 
      Console.WriteLine("Why would it throw the exception here and not where it fails to parse?"); 
     } 
    } 
} 
+1

延期執行。 –

+0

請閱讀此示例:https://blogs.msdn.microsoft.com/charlie/2007/12/10/linq-and-deferred-execution/ – Evk

回答

3

除非強制執行,不執行LINQ查詢,直到它真正需要(「延遲執行」)。它甚至可能不會被完全執行 - 只有那些需要的部分(「懶惰評估」)。

看到這個:https://msdn.microsoft.com/en-gb/library/mt693152.aspx這:https://blogs.msdn.microsoft.com/ericwhite/2006/10/04/lazy-evaluation-and-in-contrast-eager-evaluation/

您可以通過添加類似.ToList()或.ToArray(),以LINQ查詢結束時立即強制執行完畢。