我试图制作一个小型猜谜游戏,在其中生成一个随机数,用户使用TextBox
和Button
输入一个数字。目前它正在创建随机数并执行我想要的所有操作,但每次用户按下按钮上的提交时,它都会生成一个新的随机数供他们猜测
我对ASP.NET类型的东西很新,所以我的代码可能是效率低下且不正确的lol,所以我有两个特别的问题。
public partial class WebPageSeparated : System.Web.UI.Page
{
private int randNum;
private int theirGuess;
public WebPageSeparated()
{
Random randomNum = new Random();
randNum = randomNum.Next(0, 10);
theirGuess = 0;
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Guessing game! Guess a number between [0,10) to see if you can get it right!";
new WebPageSeparated();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
theirGuess = Convert.ToInt32(TextBox1.Text);
if (theirGuess != this.randNum)
{
Label1.Text = "Sorry, wrong number. Please try again!";
}
else if(theirGuess == this.randNum)
{
Label1.Text = "Correct! A new number has been generated, go ahead and try to do it again!";
new WebPageSeparated();
}
}
catch (System.FormatException)
{
Label1.Text = "Enter a number [1,10)";
}
}
}
答案 0 :(得分:0)
您的代码存在一些问题:
您永远不应该创建页面的新实例(new WebPageSeparated()
)。每次导航到页面时(通过在浏览器中输入URL)和每当导致PostBack时(例如,通过单击asp:button
),都会创建一个新实例。
如果你想要一些代码,它只在第一次调用页面时运行(即不在PostBack期间,只在导航到页面时),那么你应该将代码包装在if (!IsPostBack) {}
块中
因为为每个PostBack创建了一个新的页面实例,所以不能将任何状态(随机数)存储在页面的实例字段中。您必须找到另一个存储州的地方,例如:
private static int randNum
Session["randNum"] = randomNum.Next(0, 10)
ViewState
,例如ViewState["randNum"] = ...
考虑到所有这些要点,您的Page_Load
方法看起来像这样:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Random randomNum = new Random();
randNum = randomNum.Next(0, 10);
ViewState["randNum"] = randNum;
}
else
{
randNum = (int) ViewState["randNum"];
}
Label1.Text = "Guessing game! Guess a number between [0,10) to see if you can get it right!";
}
此外,在这种情况下,用户猜测正确的数字,您应该生成并存储一个新的随机数(在if (!IsPostBack)
内完成)。
最后,您可能希望了解更多有关的一些主题:页面生命周期,PostBack,Viewstate,会话状态
答案 1 :(得分:-2)
原因是asp.net 回发浏览器中执行的每个操作的所有数据到服务器。由于您在构造函数中生成了一个随机数,因此您面临此问题。我猜这会对你有帮助。
public partial class WebPageSeparated : System.Web.UI.Page
{
private int randNum;
private int theirGuess;
protected void Page_Load(object sender, EventArgs e)
{
Random randomNum = new Random();
randNum = randomNum.Next(0, 10);
theirGuess = 0;
Label1.Text = "Guessing game! Guess a number between [0,10) to see if you can get it right!";
new WebPageSeparated();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
theirGuess = Convert.ToInt32(TextBox1.Text);
if (theirGuess != this.randNum)
{
Label1.Text = "Sorry, wrong number. Please try again!";
}
else if(theirGuess == this.randNum)
{
Label1.Text = "Correct! A new number has been generated, go ahead and try to do it again!";
new WebPageSeparated();
}
}
catch (System.FormatException)
{
Label1.Text = "Enter a number [1,10)";
}
}