FieldInfo.GetValue 对于私有成员返回 null,而调试器指示字段不为 null?
在 C# / .NET 4.0 中,我尝试通过反射检索字段值:
var bar = foo.GetType()
.GetField("_myField", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(foo)
我对这种情况有点困惑。返回的值为 null
,但该字段(通过调试器观察时)不为 null。更令人费解的是,上面的代码适用于其他对象属性。
唯一奇怪的方面是两个标志 IsSecurityCritical
和 IsSecuritySafeCritical
为 true
,但我什至不确定它实际上与情况相关。
我最终遇到了这样一个小 HttpModule 的情况。
public class MyModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += BeginRequest;
}
void BeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
var rawContent = typeof(HttpRequest)
.GetField("_rawContent", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(app.Request);
// at this point 'rawContent' is null, while debugger indicates it is not.
}
}
有什么建议可以解释这种行为吗?
In C# / .NET 4.0 I am trying to retrieve a field value through reflection with:
var bar = foo.GetType()
.GetField("_myField", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(foo)
I am a bit puzzled by the situation. The value returned is null
, and yet, the field (when observed through the debugger) is not null. Even more puzzling, the code here above works for the other object properties.
The only odd aspect are the two flags IsSecurityCritical
and IsSecuritySafeCritical
that are true
, but I am not even sure it's actually relevant to the situation.
I am ending up in such a situation with a small HttpModule.
public class MyModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += BeginRequest;
}
void BeginRequest(object sender, EventArgs e)
{
var app = (HttpApplication)sender;
var rawContent = typeof(HttpRequest)
.GetField("_rawContent", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(app.Request);
// at this point 'rawContent' is null, while debugger indicates it is not.
}
}
Any suggestion that would explain such a behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是由 .net 4.0 中的安全模型引起的,因为您正在运行 asp.net 应用程序,该应用程序可能未在完全信任的情况下运行。由于该字段对于安全至关重要,因此您无法通过反射访问它。
您可以在 msdn 上阅读一些有关:反射的安全注意事项
This is caused by the security model in .net 4.0, as you're running an asp.net application, which is probably not running in full trust. As the field is security critical, you can't access it through reflection.
You can read a bit on the msdn about: Security Considerations for Reflection