【问题标题】:Why am I getting this Object Reference and Response not Available error?为什么我会收到此对象引用和响应不可用错误?
【发布时间】:2018-02-14 02:01:05
【问题描述】:

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
}

【问题讨论】:

    标签: c# reflection web


    【解决方案1】:

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

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

    【讨论】:

    • 我试过你说的,但是“this”不在函数的范围内,你能更具体地说一下在哪里添加这个吗??
    • 为什么我要把它传递给调用者,调用者有方法名。它与obj无关。我不明白..
    • @user287745,那是因为你的 caller 方法是静态的。而且您需要在当前页面上调用该方法,而不是在永远不会发送给客户端的新页面上。
    【解决方案2】:

    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";
    

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

    【讨论】:

    • 谢谢,你的方法很好理解如何间接访问同一页面上的内容+1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多