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()?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
You should to take a look into
System.Diagnostics.StackFrame
class. An example here: http://www.csharp-examples.net/reflection-callstack/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:
If you need to know for debugging, simple use the debugger to step through your code.
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: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.