簡體   English   中英

從反射拋出的 TargetInvocationException 是否可以具有 null InnerException

[英]Can a TargetInvocationException thrown from reflection have a null InnerException

當瀏覽器源代碼System.ComponentModel.DataAnnotations.CustomValidationAttribute 在這里,我看到了下面的代碼(縮短):

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

這里,代碼檢查ex.InnerException是否為空。 我不認為如果TargetInvocationException是從反射調用中拋出的,那么它永遠不會有null InnerException

這可能嗎? 如果是這樣,請提供一個場景,其中InnerException可以為 null。

MSDN指出

創建時,TargetInvocationException 被傳遞一個對通過反射調用的方法拋出的異常的引用。 InnerException 屬性保存基礎異常。

所以理論上只使用框架反射方法它永遠不應該為空......理論上:P

當然,如果您從正在調用的方法中顯式地拋出它,它可以(並且將會!)為 null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM