开发者

Methods A and B call method C. Now how to find out inside C who called it?

开发者 https://www.devze.com 2022-12-27 07:45 出处:网络
I have some code in method C that will开发者_运维知识库 get executed based upon the who called it.

I have some code in method C that will开发者_运维知识库 get executed based upon the who called it.

public void C()
{
    if(A called me) { .... }
    if(B called me) { .... }
}

One way is to use a flag variable. Set the variable before calling C and then inside C process the flag.

Any other ideas?


Code smell.

Why does C care about the caller ? If the code in a method is different based on who called it, maybe you need different methods

A() calls A_C()
B() calls B_C()

e.g. If class Baker supports Bake(cakeSpec), it should behave identically no matter if it is called by CustomerA or CustomerB. You may want to customize some aspects of the baking, via some configuration params in cakeSpec. However on the whole, Bake() should do what it says.

Need more info.. as to exactly what you're trying to achieve.


Look at the StackTrace class, but as Jon said, code-smell.


The following code could be used to retrieve the las calling method:

StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();


I would do this:

enum Funcs {A, B};

C(Func.A);
..
C(Func.B);


public void C(Funcs f) 
{ 
    if(f == Funcs.A) { .... } 
    if(f == Funcs.B) { .... } 
} 


I think you can use Reflection to find this out if you really want to (I haven't done it), but it's a bad idea to use that in production code. Setting the flag, as you said, is a much better idea. In fact, the flag should have a semantic meaning, rather than "who called me". Finding out the caller method is most useful for logging and other diagnostic purposes.

Edit: Tried out the Reflection approach I was thinking of (calling System.Reflection.RuntimeMethodInfo.InternalGetCurrentMethod()) and it doesn't work. :(


If this is C programming, I can achieve it by using function pointers technique provided that A and B have the same arguments. A and B will pass an identification information in one of the arguments for C to know who is calling... sort of WndProc() design in Win32 API where the message is the id and params are the data.

In C#, I think you can use delegates.


you could send a parameter to indentify which calles c, like 0 for A and 1 for B but i guess this counts as bad programming ...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号