c# - FieldInfo.GetValue 为私有(private)成员返回 null 而调试器指示字段不为 null?

标签 c# .net reflection fieldinfo

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

var bar = foo.GetType()
  .GetField("_myField", BindingFlags.Instance | BindingFlags.NonPublic)
  .GetValue(foo)

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

唯一奇怪的方面是 IsSecurityCriticalIsSecuritySafeCritical 这两个标志 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/

相关文章:

c# - 区分用于引用对象的类型及其后备存储的类型

c# - 如何对 `string.Empty` 进行哈希处理?

c# - FluentNhibernate 映射字典外键保持为空

python - 如何获取内置 Python 类构造函数的参数列表?

c# - lambda 表达式使用反射吗?

c# - 以编程方式使用具有指定位置和大小的 Windows 资源管理器打开文件夹 [C#]

c# - 参数可选时如何获取默认构造函数

c# - Azure 计算模拟器上的 Web API 失败

c# - 使用手工生成的脚本进行数据库变更管理

.NET 3.5 安全问题