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

后端 未结 19 1706
猫巷女王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 22:55

    We can also use lambda's in order to find the caller.

    Suppose you have a method defined by you:

    public void MethodA()
        {
            /*
             * Method code here
             */
        }
    

    and you want to find it's caller.

    1. Change the method signature so we have a parameter of type Action (Func will also work):

    public void MethodA(Action helperAction)
            {
                /*
                 * Method code here
                 */
            }
    

    2. Lambda names are not generated randomly. The rule seems to be: > __X where CallerMethodName is replaced by the previous function and X is an index.

    private MethodInfo GetCallingMethodInfo(string funcName)
        {
            return GetType().GetMethod(
                  funcName.Substring(1,
                                    funcName.IndexOf(">", 1, StringComparison.Ordinal) - 1)
                  );
        }
    

    3. When we call MethodA the Action/Func parameter has to be generated by the caller method. Example:

    MethodA(() => {});
    

    4. Inside MethodA we can now call the helper function defined above and find the MethodInfo of the caller method.

    Example:

    MethodInfo callingMethodInfo = GetCallingMethodInfo(serverCall.Method.Name);
    

提交回复
热议问题