0

I created this code to see, but I'm assuming that the enumerable is not being lazily evaluated when I test it.

    public void EnumerableExceptionTest_CanOnlyBeTestedByInspectingError()
    {
        var ints = GetIntsButReallyThrowError();  // error occurs here.
        var y = 10;
        var z = 11;
        foreach(var i in ints) // error *could* be on this line, but not in my tests.
        {
            Console.WriteLine(i+y+z);
        }

    }
    private IEnumerable<int> GetIntsButReallyThrowError()
    {
        var x = true;
        if (x)
        {
            throw new Exception("Threw this on purpose.");
        }
        else
        {
            return new int[]{1,2,3};
        }
    }

Is it possible though the error would not occur until it is lazily evaluated, and thus that the error line number would be that of the foreach loop?

*Note, this may be useful to keep in mind while debugging if the methodname isn't on the line that the callstack says it's on. It doesn't necessarily mean that your code / pdbs are out of date :-P

4

1 回答 1

3

问题是该结构可能会或可能不会被延迟评估,但是您的方法一被调用就会执行。由于您的 Exception 在返回任何内容之前被命中,因此该执行会抛出。

你可以试试这个。它利用yield关键字懒惰地动态构建结果:

private IEnumerable<int> GetIntsButReallyThrowError()
{
    yield return 1;
    throw new Exception("Threw this on purpose.");
}
于 2013-06-26T19:40:09.120 回答