问题
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
}
}
}
回答1:
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
}
}
}
回答2:
SecretNumber guessNr = new SecretNumber();
Isn't actually doing anything. You need:
public partial class _Default : System.Web.UI.Page
{
private SecretNumber guessNr;
protected void Page_Load(object sender, EventArgs e) {
this.guessNr = new SecretNumber();
}
protected void btnCheckNr_Click(object sender, EventArgs e) {
if (!Page.IsValid) {
return;
}
else {
var guessedNr = int.Parse(inputBox.Text);
var result = this.guessNr.MakeGuess(guessedNr);
// Now use result
}
}
}
回答3:
Put guessNr outside of Page_Load if you want to access it in btnCheckNr.
SecretNumber guessNr;
and then assign it in Page_Load Method.
回答4:
I assume that you need to read some basic info about classes in C# (fields, methods, events). This isn't an ASP.NET problem because ASP.NET follows exactly the same paradigm as any other .NET technology in terms of OOP.
Obviously you need to use the field of type SecretNumber here
来源:https://stackoverflow.com/questions/9244405/cant-access-instantiated-object-c-asp-net