C# version of __FUNCTION__ macro

后端 未结 6 1780
有刺的猬
有刺的猬 2021-02-19 01:18

Does anyone has a good solution for a C# version of the C++ __FUNCTION__ macro? The compiler does not seem to like it.

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 01:44

    What I currently use is a function like this:

    using System.Diagnostics;
    
    public string __Function() {
        StackTrace stackTrace = new StackTrace();
        return stackTrace.GetFrame(1).GetMethod().Name;
    }
    

    When I need __FUNCTION__, I just call the __Function() instead. For example:

    Debug.Assert(false, __Function() + ": Unhandled option");
    

    Of course this solution uses reflection too, but it is the best option I can find. Since I only use it for Debugging (not Tracing in release builds) the performance hit is not important.

    I guess what I should do is create debug functions and tag them with

    [ Conditional("Debug") ]
    

    instead, but I haven't got around to that.

    Thanks to Jeff Mastry for his solution to this.

提交回复
热议问题