不能访问实例化的对象C#/ asp.net [英] can't access instantiated object c#/asp.net

查看:150
本文介绍了不能访问实例化的对象C#/ asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这是一个应用程序实例从一个名为SecretNumber时,页面的GET完成类的对象。在那之后,我想与实例的实例化一个新的,而不是对象的工作。

下面是幕后文件code一块我的code,而问题是,我不能使用的按钮功能里面的对象引用。我得到一个错误,告诉该名称不会在目前的情况下存在。

这又如何解决呢?在此先感谢!

 公共部分类_Default:System.Web.UI.Page
{
    保护无效的Page_Load(对象发件人,EventArgs的发送){
        SecretNumber guessNr =新SecretNumber();
    }    保护无效btnCheckNr_Click(对象发件人,EventArgs的发送){
        如果(!Page.IsValid){
            返回;
        }        其他{
            VAR guessedNr = int.Parse(inputBox.Text);
            VAR的结果= guessNr.MakeGuess(guessedNr); < - 'guessNr'这个名字并不在目前的情况下存在
        }
    }
}


解决方案

变量该方法的范围中移动宣言,所以它成为的那种类型的私有字段 _Default

这应当制定

 公共部分类_Default:System.Web.UI.Page
{
    私人SecretNumber guessNr;    保护无效的Page_Load(对象发件人,EventArgs的发送){
        guessNr =新SecretNumber();
    }    保护无效btnCheckNr_Click(对象发件人,EventArgs的发送){
        如果(!Page.IsValid){
            返回;
        }        其他{
            VAR guessedNr = int.Parse(inputBox.Text);
            VAR的结果= guessNr.MakeGuess(guessedNr); < - 'guessNr'这个名字并不在目前的情况下存在
        }
    }
}

I have an application that's instantiates an object from a class called "SecretNumber" when a get of the page is done. After that, I want to work with the object that's instantiated instead of instantiating a new one.

Below is a piece of my code from the code behind-file, and the problem is that I can't use the object reference inside the button function. I get an error telling that the name doesn't exist in the current context.

How can this be solved? Thanks in advance!

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e) {
        SecretNumber guessNr = new SecretNumber();
    }

    protected void btnCheckNr_Click(object sender, EventArgs e) {
        if (!Page.IsValid) {
            return;
        }

        else {
            var guessedNr = int.Parse(inputBox.Text);
            var result = guessNr.MakeGuess(guessedNr); <- The name 'guessNr' does not exist in the current context
        }
    }
}

解决方案

Move declaration of the variable out of the scope of the method, so it becomes a private field of the type _Default.

This shall work

public partial class _Default : System.Web.UI.Page
{
    private SecretNumber guessNr;

    protected void Page_Load(object sender, EventArgs e) {
        guessNr = new SecretNumber();
    }

    protected void btnCheckNr_Click(object sender, EventArgs e) {
        if (!Page.IsValid) {
            return;
        }

        else {
            var guessedNr = int.Parse(inputBox.Text);
            var result = guessNr.MakeGuess(guessedNr); <- The name 'guessNr' does not exist in the current context
        }
    }
}

这篇关于不能访问实例化的对象C#/ asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆