从反射抛出的 TargetInvocationException 可以有一个 null InnerException

Can a TargetInvocationException thrown from reflection have a null InnerException

在浏览 System.ComponentModel.DataAnnotations.CustomValidationAttribute here 的源代码时,我看到了以下代码(缩写):

try
{
    methodInfo.Invoke(null, methodParams);
}
catch (TargetInvocationException ex)
{
    if (ex.InnerException != null)
    {
        throw ex.InnerException
    }
    throw;
}

此处,代码检查 ex.InnerException 是否为空。 我不认为 TargetInvocationException 可以有 null InnerException 如果它是从反射调用中抛出的。

这可能吗?如果是这样,请提供 InnerException 可以为空的场景。

MSDN 表示

When created, the TargetInvocationException is passed a reference to the exception thrown by the method invoked through reflection. The InnerException property holds the underlying exception.

所以理论上只使用框架反射方法它不应该为空...理论上 :P

当然,如果您从被调用的方法中明确抛出它,它当然可以(并且将会!)为 null。