1

我在下面有这个数学游戏,如果用户给出正确的答案,分数应该增加 5。但是,它总是卡在 5 并且永远不会增加。我想知道为什么?我声明了 !IsPostBack 变量,因此它停止重置 int,除非在页面刷新时,建议赞赏。

在此处输入图像描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{

    int score;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            score = 0;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        int sayi1;
        int sayi2;
        Random rnd = new Random();
        sayi1 = rnd.Next(0, 100);
        sayi2 = rnd.Next(0, 100);
        Label1.Text = sayi1.ToString();
        Label3.Text = sayi2.ToString();
    }


    protected void Button2_Click(object sender, EventArgs e)
    {
        int entry = Convert.ToInt32(TextBox1.Text);
        int number1 = Convert.ToInt32(Label1.Text);
        int number2 = Convert.ToInt32(Label3.Text);
        int total = number1 + number2;

        if (entry == total)
        {
            score += 5;
            Label5.Text = score.ToString();
        }
        else
        {
            score -= 2;
            Label5.Text = score.ToString();
        }
    }
}
4

2 回答 2

4

int从_

if (!IsPostBack)
{
    int score = 0;
}

您实际上是在花括号内定义一个新的整数变量,而不是更新定义为字段的变量。

于 2013-09-15T18:41:42.427 回答
2

另外,尝试使用static..

static int score;

..但这将适用于广泛的应用。

如果这需要是per-user,那么您可以使用 asession来存储增量。

if (Session["Score"] != null)
    Session["Score"] = ((int)Session["Score"]) + 5;
else
    Session["Score"] = 5;
于 2013-09-15T18:56:39.393 回答