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条回答
相关推荐>>
2楼-- · 2020-04-10 03:03

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.

查看更多
做个烂人
3楼-- · 2020-04-10 03:04
MethodBase callerMethod = new System.Diagnostics.StackFrame(1).GetMethod();

Useful if you're writing an audit / log framework, but really, YDNTN applies here. Plus it's costing a fortune at runtime.

查看更多
够拽才男人
4楼-- · 2020-04-10 03:09

Just set a breakpoint in C()

查看更多
孤傲高冷的网名
5楼-- · 2020-04-10 03:11

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.

查看更多
放荡不羁爱自由
6楼-- · 2020-04-10 03:15

The easy (and clean) way would be to introduce a new parameter to C and let A and B tell C who called it.

查看更多
不美不萌又怎样
7楼-- · 2020-04-10 03:18

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.

查看更多
登录 后发表回答