簡體   English   中英

c#:如何使用反射獲取“this”的值?

[英]c#: How to get the value of 'this' with Reflection?

有沒有辦法找出傳遞給當前代碼上方幾個堆棧幀的函數的隱式this參數的值? 我知道這聽起來很奇怪,所以讓我給你一個更大的圖景。

我正在使用一個測試自動化框架,它允許我在單獨的 .NET 程序集中插入我自己的代碼。 我的代碼是一個公共靜態方法,最終會被框架調用。 從框架的工作方式我知道我的代碼是由Run方法間接調用的。 Run是實現ITestModule接口的類的非靜態方法。

我的代碼想要訪問其Run方法正在執行的實例中的非靜態屬性,或者換句話說, Run方法的隱式this的屬性成員。

到目前為止,我編寫的代碼使用StackTrace類遍歷堆棧並詢問每個堆棧幀其方法是否具有我期望的簽名。 一旦找到匹配項,代碼就會向方法的ReflectedType詢問底層類,從中獲取所請求屬性的PropertyInfo 如果現在我也有this ,我可以繼續調用MethodInfo.GetMethod.Invoke來檢索屬性值。

這是代碼,省略了錯誤檢查等。

StackTrace st = new StackTrace();
for (int j = 0; j < st.FrameCount; ++j)
{
  // examine each stack frame until we find what we are looking for
  StackFrame frame = st.GetFrame(j);
  MethodBase method = frame.GetMethod(); // executing method
  if (method.ToString() == "<method signature>")
  {
    // We have found the "Run" method
    Type rType = method.ReflectedType; // class of which "Run" is a member
    PropertyInfo pInfo = rType.GetProperty(property_name); // the property
    MethodInfo propGet = pInfo.GetMethod; // the property's "get" accessor

    Object instance = ...; // The "this" of the "Run" method
    Object result = propGet.Invoke(instance, null); // Retrieve the property value
    // do something with result

    break;
  }
}

它是Object instance = ...; 讓我頭疼的線路。

非常感謝您的任何建議。

漢斯

顯然,答案是“沒有辦法做到這一點”。 此外,我找到了一個更好的方法,使用該框架中的函數。 (我只是發布這個答案,以便我可以將問題標記為已回答。)

暫無
暫無

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

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