在 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.
}
}
有什么建议可以解释这种行为吗?
最佳答案
这是由 .net 4.0 中的安全模型引起的,因为您正在运行一个 asp.net 应用程序,它可能没有以完全信任的方式运行。由于该字段对安全至关重要,因此您无法通过反射访问它。
您可以在 msdn 上阅读一些内容:Security Considerations for Reflection
关于c# - FieldInfo.GetValue 为私有(private)成员返回 null 而调试器指示字段不为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4441561/