扩展方法没有按预期抛出异常

Extension method doesn't throw exception as expected

I have the following extension methods:

public static T ToObject<T>(this DataRow row) where T : new()
{
    if (row == null) throw new ArgumentNullException("row");

    // do something
}

public static IEnumerable<T> ToObject<T>(this DataTable table) where T : new()
{
    if (table == null) throw new ArgumentNullException("table");

    // do something
}

以及各自的测试:

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullDataRow()
{
    // Arrange
    DataRow row = null;

    // Act
    row.ToObject<SomeData>();
}

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullDataTable()
{
    // Arrange
    DataTable table = null;

    // Act
    table.ToObject<SomeData>();
}

DataRow test passes (it throws ArgumentNullException normally) while the DataTable one 没有(既不命中方法也不抛出任何东西)。

我完全不知道为什么 DataTable 测试不起作用(而 DataRow 测试正常!)。

(起初我以为是我的 Visual Studio 中的错误,但 the CI service that I use accused the same

我假设 IEnumerable<T> 不只是为了好玩,而且扩展方法实际上是一个迭代器。

这样的迭代器,在你开始迭代之前,实际上并没有执行到抛出异常的地步。

您在此处发布的代码不足以诊断问题,因为它是由隐藏在 /// do something 评论后面的内容引起的。查看 github 上的代码:

public static IEnumerable<T> ToObject<T>(this DataTable table) where T : new()
{
    if (table == null) throw new ArgumentNullException("table");
    foreach (DataRow row in table.Rows) yield return ToObject<T>(row, false);
}

yield return 使得该方法在需要结果(执行迭代)之前不会实际执行任何代码。

为了使其工作遵循 .NET 团队在 LINQ 实现中使用的相同模式:

public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector) {
    if (source == null) throw Error.ArgumentNull("source");
    if (selector == null) throw Error.ArgumentNull("selector");
    return SelectIterator<TSource, TResult>(source, selector);
}

其中 SelectIterator 使用 yield return 一次 return 一项。