How can I know which method call my method?

2020-04-10 03:00发布

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# .net c#-3.0
9条回答
Viruses.
2楼-- · 2020-04-10 03:23
时光不老,我们不散
3楼-- · 2020-04-10 03:24

Method C() should not need to know which method called it. If this is how you are handling your flow logic, you need to think again about how you are writing your code. If we assume that there is some valid reason for needing to know which method called C(), I would create two 'wrapper' methods: C_From_A() and C_From_B(). Any logic specific to the calling methods should be moved to the new methods, while common code is left in the C() method and called from both the new methods:

public void C()
{
   // Common Code goes here
}

public void C_From_A()
{
    // Code only to be called from A() goes here.

    C();  // Common code executed
}

public void C_From_B()
{
    // Code only to be called from B() goes here.

    C();  // Common code executed
}


public void A()
{
    // Other code goes here

    C_From_A();
}

If you need to know for debugging, simple use the debugger to step through your code.

查看更多
Deceive 欺骗
4楼-- · 2020-04-10 03:27

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"
}

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.

查看更多
登录 后发表回答