[英]c#: How to get the value of 'this' with Reflection?
有没有办法找出传递给当前代码上方几个堆栈帧的函数的隐式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 = ...;
让我头疼的线路。
非常感谢您的任何建议。
汉斯
显然,答案是“没有办法做到这一点”。 此外,我找到了一个更好的方法,使用该框架中的函数。 (我只是发布这个答案,以便我可以将问题标记为已回答。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.