我怎样才能知道哪些方法调用我的方法? [英] How can I know which method call my method?

查看:182
本文介绍了我怎样才能知道哪些方法调用我的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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.

这篇关于我怎样才能知道哪些方法调用我的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆