簡體   English   中英

FieldInfo.GetValue為私有成員返回null,而調試器指示字段為非null?

[英]FieldInfo.GetValue return null for a private member while debugger indicates field is non null?

在C#/ .NET 4.0中,我試圖通過反射檢索字段值:

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

我對這種情況感到有些困惑。 返回的值為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.
    }
}

任何可以解釋這種行為的建議?

這是由.net 4.0中的安全模型引起的,因為您正在運行一個asp.net應用程序,該應用程序可能無法完全信任。 由於該字段對安全性至關重要,因此無法通過反射訪問它。

您可以在msdn上閱讀一些關於: 反射的安全注意事項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM