我正在使用LINQ查询将输入字符串解析为类。我已将查询包装在try / catch块中以处理解析错误。问题是异常没有在我期望它发生的时刻捕获,它只在访问结果对象(parsedList
)的位置停止程序流。我是否误解了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?");
}
}
}
答案 0 :(得分:3)
除非强制执行,否则在实际需要之前不会执行LINQ查询(&#34;延迟执行&#34;)。它甚至可能不会被完全执行 - 只需要那些需要的部分(&#34;惰性评估&#34;)。
请参阅:JSFIDDLE DEMO和此:https://msdn.microsoft.com/en-gb/library/mt693152.aspx
您可以通过在Linq查询的末尾添加.ToList()或.ToArray()等内容来立即强制执行完整的执行。