c#:如何使用反射获取"this"的值?



有没有办法找出传递到当前代码上方几个堆栈帧的函数中的隐式this参数的值?我知道这听起来很奇怪,所以让我给你一个更大的画面。

我正在使用一个用于测试自动化的框架,该框架允许我在一个单独的.NET程序集中插入自己的代码。我的代码是一个公共静态方法,它最终被框架调用。从框架的工作方式来看,我知道我的代码是由Run方法间接调用的。Run是实现ITestModule接口的类的非静态方法。

我的代码想要访问其Run方法正在执行的实例中的非静态属性,或者换句话说,访问Run方法的隐式this的属性成员。

到目前为止,我编写的代码使用StackTrace类遍历堆栈,并询问每个堆栈帧的方法是否具有我所期望的签名。一旦找到匹配项,代码就会向方法的ReflectedType询问底层类,从中获得所请求属性的PropertyInfo。如果现在我也有this,我可以继续调用MethodInfo.GetMethod.Invoke来检索属性值。

这是代码,省略了错误检查等

StackTrace st = new StackTrace();
for (int j = 0; j < st.FrameCount; ++j)
{
// examine each stack frame until we find what we are looking for
StackFrame frame = st.GetFrame(j);
MethodBase method = frame.GetMethod(); // executing method
if (method.ToString() == "<method signature>")
{
// We have found the "Run" method
Type rType = method.ReflectedType; // class of which "Run" is a member
PropertyInfo pInfo = rType.GetProperty(property_name); // the property
MethodInfo propGet = pInfo.GetMethod; // the property's "get" accessor
Object instance = ...; // The "this" of the "Run" method
Object result = propGet.Invoke(instance, null); // Retrieve the property value
// do something with result
break;
}
}

让我头疼的是Object instance = ...;线路。

非常感谢你的建议。

汉斯

显然,答案是"没有办法做到这一点";。此外,我找到了一个更好的方法,在这个框架中使用一个函数。(我只是发布这个答案,这样我就可以将问题标记为已回答。(

最新更新