我正在使用 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?");
}
}
}
Run Code Online (Sandbox Code Playgroud)
除非强制执行,否则 LINQ 查询只有在实际需要时才会执行(“延迟执行”)。它甚至可能不会被完全执行——只执行那些需要的部分(“惰性求值”)。
请参阅: https: //msdn.microsoft.com/en-gb/library/mt693152.aspx和此: https: //blogs.msdn.microsoft.com/ericwhite/2006/10/04/lazy-evaluation-and -对比渴望评估/
您可以通过将 .ToList() 或 .ToArray() 之类的内容添加到 Linq 查询的末尾来强制立即完整执行。