2016-11-08 64 views
1

我想定義一個擴展方法,該方法遞歸到嵌套結構中,您猜對了異常。這是我想怎麼辦...無法定義遞歸的擴展方法

class Utils 
{ 
    public static string TellMeEverything(this Exception ex) 
    { 
     return ex.InnerException?.TellMeEverything() + ex.Message + ex.StackTrace; 
    } 
} 

但這生成編譯器錯誤'Exception' does not contain a definition for 'TellMeEverything' and no extension method 'TellMeEverything' accepting a first argument of type 'Exception' could be found (are you missing a using directive or an assembly reference?)

難道這被認爲是一個編譯器錯誤?

+3

不應該'?.'訪問是對'InnerException'而不是'ex'?如果'ex'爲null,你已經保護了內部的'TellMeEverything'調用,但是你仍然會在'ex.Message'上冒充空引用。 –

+0

哦,我的天啊,我必須醒來。 – bbsimonbb

回答

5

class utils也應該public static,以便它能夠被發現的一個擴展System.Exception