How to get the name of the call method?

Can the class A log method know who calls it?

class A
{
    public void Log(string msg)
    {
        Log.Write("method_name: " + msg);
    }
}

I want to know the class name and method name.

+5
source share
5 answers

You can use StackTraceand StackFrame. You can get an entire stack trace by calling the constructor StrackTraceor just a specific stack of the stack using the constructor StackFrame, which accepts the number of skipped frames.

You should be aware that this may not be accurate due to the attachment. (method e..g In method B, which calls your method - method A will be reported, not B).

Code example:

using System;
using System.Diagnostics;

class Test
{
    static void ShowCaller()
    {
        // Use this code if you want multiple frames
        // StackTrace trace = new StackTrace();
        // StackFrame frame = trace.GetFrame(1);

        // Use this code if you're only interested in one frame
        StackFrame frame = new StackFrame(1);
        Console.WriteLine(frame.GetMethod());
    }

    static void Intermediate()
    {
        ShowCaller();
    }

    static void Main()
    {
        Intermediate();
    }
}

, Void Main() - Intermediate(), Void Intermediate().

( , . , , .)

+4

+2

:

 class staitc A
    {
        public staitc  void Log(string msg)
        {
            Log.Write("method_name: " + msg);
        }
    }


        using System.Reflection;

class TestClass
{
       // in method

        private void TestMethod()
    {
           A.Log(MethodBase.GetCurrentMethod().Name +MethodBase.GetCurrentMethod().DeclaringType.FullName);
    }
}
+1

, - StackTrace, stackTrace.GetFrame(1).GetMethod().Name - , , , , .

0

.NET 4.5 CallerMemberNameAttribute, System.Runtime.CompilerServices:

using System.Runtime.CompilerServices;

class A
{
    public void Log(string msg, [CallerMemberName] string memberName = "")
    {
        Log.Write("{0}: {1}", memberName, msg);
    }
}
0

All Articles