为什么我收到此对象引用和响应不可用错误?

时间:2010-10-20 09:01:47

标签: c# reflection web

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
}

2 个答案:

答案 0 :(得分:3)

您似乎希望使用当前页面(_default的实例)而不是创建新页面。

尝试将this传递给来电者,并用它替换obj

答案 1 :(得分:1)

Response属于设置为Page的HttpContext属性的当前Response,我猜你使用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";

这正是我的意思。但你真的需要这样做,还是只是为了练习。