【问题标题】:Exception from LINQ query not caught where expectedLINQ 查询的异常未在预期的地方捕获
【发布时间】:2016-06-14 15:23:02
【问题描述】:

我正在使用 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?");
        }
    }
}

【问题讨论】:

标签: c# linq exception-handling


【解决方案1】:

除非您强制执行,否则 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/

您可以通过在 Linq 查询末尾添加 .ToList() 或 .ToArray() 之类的内容来强制立即执行完整。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 2017-05-10
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    相关资源
    最近更新 更多