简体   繁体   English

如何知道调用哪个方法的对象?

[英]How to know object from which method is called?

I have a static class, which methods is called from instances of another class. 我有一个静态类,从另一个类的实例调用哪些方法。 How I can to know which instance has called method without some adding method parameters ? 如何在没有添加方法参数的情况下知道哪个实例调用了方法?

Example: 例:

static class SomeStaticClass
{
 public static void SomeGreatMethod (/*NO PARAMETERS*/)
 {
   LittleClass caller = //How to obtain caller instance here?
 }
}

class LittleClass
{
 public void SomeMethod ()
 {
   //some code
   SomeStaticClass.SomeGreatMethod (/*NO PARAMETERS*/);
 }
}

You can potentially find out which class contains the calling method by creating a stack trace - although inlining can mess this up. 您可以通过创建堆栈跟踪来找出哪个包含调用方法 - 尽管内联可能会弄乱这一点。

You can't find out which instance is making the call unless you're using the debugging API. 除非您使用调试API,否则无法找出正在进行调用的实例

If you need to do either of these things, you've probably got a design problem. 如果你需要做其中任何一件事,你可能会遇到设计问题。 There are some areas of the framework which do something similar to impose security, but that's a pretty rare case. 框架的某些区域做了类似于强制安全的事情,但这是一种非常罕见的情况。 Normally, if you need that information in SomeGreatMethod , you should simply provide it as part of the call - or make it an instance method in a non-static class, and provide the appropriate contextual information on construction. 通常,如果在SomeGreatMethod需要该信息, SomeGreatMethod应该只是将其作为调用的一部分提供 - 或者将其作为非静态类中的实例方法,并提供有关构造的相应上下文信息。

您可以获取StackFrame并从中读取整个堆栈跟踪

Take a look here, you need to use the callstack 看看这里,你需要使用callstack

http://www.csharp-examples.net/reflection-calling-method-name/ http://www.csharp-examples.net/reflection-calling-method-name/

Sometimes I use this 有时候我会用它

private static Type GetCallingMethodHolderType()
{
   const int iCallDeepness = 0; //can vary this ...
   System.Diagnostics.StackTrace stack = new System.Diagnostics.StackTrace(false);
   System.Diagnostics.StackFrame sframe = stack.GetFrame(iCallDeepness);
   return sframe.GetMethod().ReflectedType; //This will return a TYPE which holds the method.
}

EDIT 编辑

I edited the post in order to return the TYPE of the object wich holds the caller method. 我编辑了帖子,以便返回保存调用方法的对象的TYPE。 Instance , like you requested, imo, it's not possible to get. 实例 ,就像你要求的那样,imo,它是不可能获得的。

Should work for you. 应该适合你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM