How can I find the method that called the current method?

后端 未结 19 1726
猫巷女王i
猫巷女王i 2020-11-21 22:50

When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but

19条回答
  •  无人及你
    2020-11-21 23:19

    You can use Caller Information and optional parameters:

    public static string WhoseThere([CallerMemberName] string memberName = "")
    {
           return memberName;
    }
    

    This test illustrates this:

    [Test]
    public void Should_get_name_of_calling_method()
    {
        var methodName = CachingHelpers.WhoseThere();
        Assert.That(methodName, Is.EqualTo("Should_get_name_of_calling_method"));
    }
    

    While the StackTrace works quite fast above and would not be a performance issue in most cases the Caller Information is much faster still. In a sample of 1000 iterations, I clocked it as 40 times faster.

提交回复
热议问题