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 资料的方法
In the case where you're trying to figure out where a "bad parameter was passed" you only need to set a conditional breakpoint in that method or have VS break on the exception that would be thrown and then you can examine the call stack (Debug Menu, Window, Call Stack) to see the entire chain of callers (with arguments passed) to this method.
Useful if you're writing an audit / log framework, but really, YDNTN applies here. Plus it's costing a fortune at runtime.
Just set a breakpoint in C()
You shouldn't need to. Some method should perform a specific task, which is influenced by its parameters and the object attributes, not the caller.
The easy (and clean) way would be to introduce a new parameter to
C
and letA
andB
tellC
who called it.I agree in principle you shouldn't need to know in most situations.
However the one use case where this may be useful to know is when debugging where certain information came from, In the case of a bad parameter passed.
However in that case its probably better to throw an exception, log the exception and "recover" from it. Obviously this depends on how often the method is called as there is always some overhead with creating an exception. If you need to do this for some other reason than I would suggest you look at your design first.
If you need callbacks I would suggest that you make A and B both implement an interface and pass A or B as a parameter. The interface could have a method called callback and C could call A or B.