C# 分数整数被卡住,尽管它是';他宣布了!IsPostBack声明

C# 分数整数被卡住,尽管它是';他宣布了!IsPostBack声明,c#,asp.net,C#,Asp.net,我有下面这个数学游戏,如果用户给出正确答案,分数应该增加5分。然而,它总是停留在5,永远不会燃烧。我想知道为什么?我宣布!IsPostBack变量,因此它会停止重置整型,除非在页面刷新时重置整型 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public parti

我有下面这个数学游戏,如果用户给出正确答案,分数应该增加5分。然而,它总是停留在5,永远不会燃烧。我想知道为什么?我宣布!IsPostBack变量,因此它会停止重置整型,除非在页面刷新时重置整型

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();
        }
    }
}


从中删除
int

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

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

从中删除
int

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

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

此外,请尝试使用
静态

static int score;
…但这将是广泛应用的

如果需要为每个用户设置,则可以使用
会话来存储增量

if (Session["Score"] != null)
    Session["Score"] = ((int)Session["Score"]) + 5;
else
    Session["Score"] = 5;

另外,尝试使用
静态

static int score;
…但这将是广泛应用的

如果需要为每个用户设置,则可以使用
会话来存储增量

if (Session["Score"] != null)
    Session["Score"] = ((int)Session["Score"]) + 5;
else
    Session["Score"] = 5;

这是一个不同的分数。这是一个不同的分数。@codingfreak,小心静态…如果这只是一个你正在搞乱的东西,并且不向多个用户开放,那么它是好的。但是,如果您正在考虑让多个用户都可以使用此功能,那么您需要使用
会话
视图状态
@codingfreak,请小心使用静态功能…如果这只是一个您正在处理的问题,并且不向多个用户开放,那么就可以了。但是,如果您想让多个用户都可以使用此功能,则需要使用
session
viewstate