Getting the instance that called the method in C#

后端 未结 5 1398
有刺的猬
有刺的猬 2021-02-18 16:05

I am looking for an algorithm that can get the object that called the method, within that method.

For instance:

public class Class1 {

    public void Me         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-18 16:25

    Here's an example of how to do this...

    ...
    using System.Diagnostics;
    ...
    
    public class MyClass
    {
    /*...*/
        //default level of two, will be 2 levels up from the GetCaller function.
        private static string GetCaller(int level = 2)
        {
            var m = new StackTrace().GetFrame(level).GetMethod();
    
            // .Name is the name only, .FullName includes the namespace
            var className = m.DeclaringType.FullName;
    
            //the method/function name you are looking for.
            var methodName = m.Name;
    
            //returns a composite of the namespace, class and method name.
            return className + "->" + methodName;
        }
    
        public void DoSomething() {
            //get the name of the class/method that called me.
            var whoCalledMe = GetCaller();
            //...
        }
    /*...*/
    }

    Posting this, because it took me a while to find what I was looking for myself. I'm using it in some static logger methods...

提交回复
热议问题