我怎样才能知道哪些方法调用我的方法?我的、方法

由网友(情话再甜只是敷衍)分享简介:我有3个方法A(),B()和C(),这两个A()和B()调用C()。在方法C(),我怎么能知道它从A()或B()?I've 3 methods A(), B() and C(), both A() and B() call C(). In method C(), how can I know it call from...

我有3个方法A(),B()和C(),这两个A()和B()调用C()。在方法C(),我怎么能知道它从A()或B()?

I've 3 methods A(), B() and C(), both A() and B() call C(). In method C(), how can I know it call from A() or B()?

推荐答案

我不推荐这种方法 - 其他海报指出,处理这个更好的方法。但是,如果你真的,真的需要知道谁给你打电话,不改变 C()的参数,你可以这样做:

I don't recommend this approach - other posters point out better ways of handling this. But if you really, really need to know who called you, without changing C()'s parameters, you can do this:

static void A()
{
    C();
}

static void C()
{
    StackTrace st = new StackTrace();
    Console.WriteLine(st.GetFrame(1).GetMethod().Name); // prints "A"
}

需要注意的是产生一个堆栈跟踪是有点昂贵。没什么大不了的,不过,除非你正在做的code,我们在调用非常频繁。

Note that generating a StackTrace is somewhat costly. Not a big deal, though, unless you're doing it in code that you're calling very frequently.

此外,你几乎肯定会发现做任何你想做的更好的方法。

Again, you almost certainly find a better way of doing whatever you're trying to do.

阅读全文

相关推荐

最新文章