得到一个方法的调用者在C#

得到一个方法的调用者在C#

问题描述:

有没有办法来获取所谓的一些方法类的实例?

is there a way to get the instance of class that called some method?

您可以得到的命名,通过检查调用堆栈调用方法的的。获取的类实例的是一个不同的故事,并且不容易实现(如果连可能的;我从来没有试过这样做)。你应该例如考虑你的方法是从静态方法调用,在这种情况下,没有类实例发现的可能性。

You can get the name of the method that calls by examining the call stack. Getting the class instance is a different story, and is not easily achieved (if even possible; I never really tried to do it). You should for instance consider the possibility that your method is called from a static method, in which case there is no class instance to find.

无论哪种方式,这通常不是做一件好事。如果该方法需要访问任何类实例调用了进去,添加作为方法的参数。

Either way, this is usually not a good thing to do. If the method needs access to whatever class instance that calls into it, add that as a parameter in the method.