有没有办法在c#中获取对调用对象的引用?

时间:2009-01-07 14:43:38

标签: c# reflection

我想知道的是,是否可以(例如)走向堆栈帧,检查每个调用对象以查看是否与接口匹配,如果是,则从中提取一些数据。

是的,我知道这是不好的做法,我想知道是否可能。

3 个答案:

答案 0 :(得分:20)

不,没有 - 至少没有使用某些描述的分析/调试API。您可以遍历堆栈以查找调用方法,但需要注意的是,由于JIT优化,它非常慢并且可能不准确。这不会告诉你调用对象是什么(如果确实有的话)。

答案 1 :(得分:3)

如果您想获得该类型,可以试试这个:

new StackFrame(1).GetMethod()。DeclaringType

正如乔恩指出的那样,如果遇到jit优化问题可能会出现问题。

至于从对象获取数据,我认为不可能。

修改

只是详细说明优化问题,请使用以下代码:

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();

        }
    }

我们应该让Program到控制台两次,当你在调试器中运行时。在没有调试器的情况下在发布模式下运行时,您将获得第一个Test函数的输出。这可能是因为要内联复杂;但是,第二种方法会导致空引用异常。

此代码的另一个危险是,MS改进了JIT编译器,可能在2.0中工作的可能会在将来的版本中崩溃和刻录。

答案 2 :(得分:0)

看到这个问题:
Can you use reflection to find the name of the currently executing method?

这不是重复,但这个问题的答案也会回答你的问题。