获取栈帧的运行时类型类型

由网友(西瓜不懂柠檬的酸)分享简介:我在想,如果有可能获得方法调用者的堆栈跟踪的运行时类型。I was wondering if it were possible to obtain the run time type of method callers in the stack trace.请看下面的例子:class Parent{public...

我在想,如果有可能获得方法调用者的堆栈跟踪的运行时类型。

I was wondering if it were possible to obtain the run time type of method callers in the stack trace.

请看下面的例子:

class Parent
{
    public void Foo()
    {
        var stack = new StackTrace();

        foreach (var frame in stack.GetFrames())
        {
            var methodInfo = frame.GetMethod();
            Console.WriteLine("{0} (ReflectedType: {1})", methodInfo.ToString(), methodInfo.DeclaringType);
        }
    }
}

class Child : Parent
{
}

如果我创建儿童的实例并调用美孚

If I create an instance of Child and call Foo

var child = new Child();
child.Foo();

美孚将打印: 无效美孚()(ReflectedType:家长)

Foo will print: Void Foo() (ReflectedType: Parent)

有没有什么办法让方法调用者的实际运行时类型(儿童在这种情况下)的堆栈跟踪?

Is there any way to get the actual run time types (Child in this case) of method callers in the stack trace?

推荐答案

没有。究其原因是由雷蒙德陈这里描述。

No. The reason is described by Raymond Chen here.

相关报价为:

在code块的对象可以执行一个功能叫的过程中变得符合回收。

An object in a block of code can become eligible for collection during execution of a function it called.

这不是直观的,了解JIT和GC一起工作的一部分。

It's not intuitive, read the part about JIT and GC working together.

获取实际类型需要实例,但优化工作主要面向制造的垃圾,所以你不能依靠它仍然在那里。

Getting the actual Type requires the instance, but the optimization effort is geared toward making that Garbage, so you can't rely on it still being there.

阅读全文

相关推荐

最新文章