有没有办法通过System.Reflection,System.Diagnostics或其他来获取对实际实例的引用,而实际实例正在调用静态方法而不将它传递给方法本身?我可以通过反射/诊断从方法中获取调用实例吗?
例如,东西沿着这些线路
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类型,但有一种方式来获得实际的实例的引用?
我意识到反射和性能问题以及静态调用的问题,而且这通常可能甚至几乎是通用的,而不是正确的解决方法。这个问题的部分原因是我很好奇它是否可行;我们目前正在传递比如在。
ExecuteMethod(instance)
而我只是想知道,如果这是可能的,并且仍然能够访问实例。
ExecuteMethod()
@Steve库珀: 我没有考虑扩展方法。一些变化可能会奏效。
这是解决这个问题的非常优雅的方法 – ohmusama 2016-06-06 22:11:58