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?");
}
}
}
延期執行。 –
請閱讀此示例:https://blogs.msdn.microsoft.com/charlie/2007/12/10/linq-and-deferred-execution/ – Evk