FieldInfo.GetValue为私有成员返回null,而调试器指示字段为非null?

Joa*_*rel 3 .net c# reflection fieldinfo

在C#/ .NET 4.0中,我试图通过反射检索字段值:

var bar = foo.GetType()
  .GetField("_myField", BindingFlags.Instance | BindingFlags.NonPublic)
  .GetValue(foo)
Run Code Online (Sandbox Code Playgroud)

我对这种情况感到有些困惑.返回的值是null,但是,字段(通过调试器观察时)不为null.更令人费解的是,上面的代码适用于其他对象属性.

唯一奇怪的是纵横两个标志IsSecurityCriticalIsSecuritySafeCriticaltrue的,但我什至不知道它实际上相关的情况.

我在一个小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.
    }
}
Run Code Online (Sandbox Code Playgroud)

任何可以解释这种行为的建议?

Jb *_*ain 5

这是由.net 4.0中的安全模型引起的,因为您正在运行一个asp.net应用程序,该应用程序可能无法完全信任.由于该字段对安全性至关重要,因此无法通过反射访问它.

您可以在msdn上阅读一些关于:反射的安全注意事项