2010-10-20 61 views
0

this question我發現了以下,但有兩個我無法解決的錯誤。爲什麼我得到這個對象引用和響應不可用錯誤?

該錯誤與聲明引起它爲***//error is***

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Reflection; 
//using System.Collections; 

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     string function_name; 
     function_name = "one"; 
     caller(function_name); 
    } 

    static void caller(String function_name) 
    { 
     // Get a type from the string 
     Type type = typeof(_Default); 
     // Create an instance of that type 
     Object obj = Activator.CreateInstance(type); 
     // Retrieve the method you are looking for 
     MethodInfo methodInfo = type.GetMethod(function_name); 
     // Invoke the method on the instance we created above 
     methodInfo.Invoke(obj, null); 
    } 

    public void one() //function 
    { 
     string a = "\n this is the alphabet a \n"; 

     ***//error is*** 
     ////Object reference not set to an instance of an object. 
     ////Label1.Text = "one i called"; 

     ***//error is*** 
     /////Response is not available in this context. 
     //// Response.Write(a); 
    }// function one ends 
} 

回答

3

它看起來像你想使用當前頁面(_default的實例),而不是創建一個新的。

嘗試將this傳入呼叫者,並用它替換obj

+0

這就是你的解決方案 – 2010-10-20 09:06:18

+0

我試過你說的,但「這個」並不在函數的範圍內,你會更具體地說明在哪裏添加這個? – user287745 2010-10-20 09:16:26

+0

以及爲什麼我將此傳遞給調用者,調用者擁有方法名稱。它與obj沒有任何關係。我不明白.. – user287745 2010-10-20 09:21:51

1

Response屬於被設置爲頁面的Response屬性的當前HttpContext和你沒有得到使用Activator.CreateInstance()我想正確的上下文。如果您使用HttpContext.Current.Response.Write(a)而不是Response.Write(a),它的工作原理:

HttpContext.Current.Response.Write(a) 

對於標籤的情況下,你需要:

Label lbl = (HttpContext.Current.Handler as Page).FindControl("Label1") as Label; 
lbl.Text = "one i called"; 

這究竟你的意思,我猜。但是你是否真的需要這樣做,還是僅僅是爲了練習。

+0

沒關係,但標籤呢?和其他功能 – user287745 2010-10-20 09:23:35

+0

我已添加標籤案例。 – 2010-10-20 09:24:35

+0

謝謝,你的方法很好理解如何間接訪問同一頁上的東西+1 – user287745 2010-10-20 09:29:19

相關問題