Getting the instance that called the method in C#

后端 未结 5 1395
有刺的猬
有刺的猬 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...

    0 讨论(0)
  • 2021-02-18 16:32

    You could get to the current stack trace in code and walk up one step. http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx

    But as was commented below, this will get you the method and class calling you, but not the instance (if there is one, could be a static of course).

    0 讨论(0)
  • 2021-02-18 16:37

    It would be very bad style since

    a) that would break encapsulation
    b) it's impossible to know the type of the calling object at compile-time so whatever you do with the object later, it will propably not work.
    c) it would be easier/better if you'd just pass the object to the constructor or the method, like:

    Class1 c1 = new Class1(object1);
    
    0 讨论(0)
  • 2021-02-18 16:40

    or just pass the object as method parameter.

    public void Method(object callerObject)
    {
    ..
    }
    

    and call the Method:

    myClass.Method(this);
    

    regards, Florian

    0 讨论(0)
  • 2021-02-18 16:45

    Obviously i don't know the exact details of your situation but this really seems like you need to rethink your structure a bit.

    This could easily be done if proper inheritance is structured.

    Consider looking into an abstract class and classes that inherit from said abstract class. You might even be able to accomplish the same thing with interfaces.

    0 讨论(0)
提交回复
热议问题