我可以从通过反射/诊断方法中得到调用实例?反射、实例、方法

2023-09-03 03:48:36 作者:帆布素颜女汉子

有没有通过的System.Reflection,System.Diagnostics程序或其他的方式来获得一个对被调用静态方法没有传递给它的方法本身的实际情况?

Is there a way via System.Reflection, System.Diagnostics or other to get a reference to the actual instance that is calling a static method without passing it in to the method itself?

例如,这些方针的东西

class A
{
    public void DoSomething()
    {
        StaticClass.ExecuteMethod();
    }
}

class B
{
    public void DoSomething()
    {
        SomeOtherClass.ExecuteMethod();
    }
}
public class SomeOtherClass
{
    public static void ExecuteMethod()
    {
        // Returns an instance of A if called from class A
        // or an instance of B if called from class B.
        object caller = getCallingInstance();
    }
}

我可以使用 System.Diagnostics程序的类型。 StackTrace.GetFrames 的,但有一种方式来获得一个引用到实际的实例?

I can get the type using System.Diagnostics.StackTrace.GetFrames, but is there a way to get a reference to the actual instance?

我知道与反思和性能问题,以及静态静态调用,并认为这是一般,甚至几乎univerally,不正确的方式来处理这个。对这个问题的部分原因是我很好奇,如果它是可行的;我们目前正在传递的实例。

I am aware of the issues with reflection and performance, as well as static to static calls, and that this is generally, perhaps even almost univerally, not the right way to approach this. Part of the reason of this question is I was curious if it was doable; we are currently passing the instance in.

ExecuteMethod(instance)

和我只是想知道这是可能的,仍然能够访问实例。

And I just wondered if this was possible and still being able to access the instance.

ExecuteMethod()

@Steve库珀: 我没有考虑扩展方法。那一些变化可能会奏效。

@Steve Cooper: I hadn't considered extension methods. Some variation of that might work.

推荐答案

我不相信你可以。即使是堆栈跟踪和的StackFrame类只是给你命名的信息,不能访问实例。

I do not believe you can. Even the StackTrace and StackFrame classes just give you naming information, not access to instances.

我不知道到底为什么你会想这样做,但要知道,即使你能做到这一点,它可能会很慢。

I'm not sure exactly why you'd want to do this, but know that even if you could do it it would likely be very slow.

有一个更好的解决办法是调用ExecuteMethod,你可以在其中检索或只是通过实例之前推实例线程当地情况。

A better solution would be to push the instance to a thread local context before calling ExecuteMethod that you can retrieve within it or just pass the instance.