Is there any way to get a reference to the calling object in c#?

前端 未结 3 1969
遥遥无期
遥遥无期 2020-12-03 09:59

What I\'m wondering is if it\'s possible to (for instance) to walk up the stack frames, checking each calling object to see if matches an interface, and if so extract some d

3条回答
  •  孤城傲影
    2020-12-03 10:43

    If you want to get the type you can try this:

    new StackFrame(1).GetMethod().DeclaringType

    As Jon pointed out there might be issues if you run into JIT optimizations.

    As for getting data from the object, I don't think it's possible.

    Edit

    Just to elaborate on the optimization issue, take the following code:

    class stackTest
    {
        public void Test()
        {
            StackFrame sFrame = new StackFrame(1);
            if (sFrame == null)
            {
                Console.WriteLine("sFrame is null");
                return;
            }
    
            var method = sFrame.GetMethod();
    
            if (method == null)
            {
                Console.WriteLine("method is null");
                return;
            }
            Type declaringType = method.DeclaringType;
            Console.WriteLine(declaringType.Name);
        }
    
        public void Test2()
        {
            Console.WriteLine(new StackFrame(1).GetMethod().DeclaringType.Name);
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
    
            stackTest s = new stackTest();
            s.Test();
            Console.WriteLine("Doing Test2");
            s.Test2();
            Console.ReadLine();
    
        }
    }
    

    We should get Program to the console twice, and when you run within the debugger you do. When you run without the debugger in release mode, you get the output from the first Test function. Which is probably because it is to complex to be inlined, however, the second method causes a null reference exception.

    Another danger with this code is that at MS improves the JIT compiler what might have worked in 2.0 could crash and burn in future versions.

提交回复
热议问题