Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Visual Studio Windows应用程序-在标签中显示数字_C# - Fatal编程技术网

C# Visual Studio Windows应用程序-在标签中显示数字

C# Visual Studio Windows应用程序-在标签中显示数字,c#,C#,我想做一个简单的增量游戏。 我有一个按钮来“建造小屋”。基本上,每次按下int值时,将其加1。然后我想在标签上显示建造了多少间小屋。但是label1.Text只接受字符串值 但是,当我转换integer.ToString时,它不起作用。它将数字保持在1,而不增加 public void Button1_Click(object sender, EventArgs e) { int numberofhuts = 0; numberofhuts++; label1.Text

我想做一个简单的增量游戏。 我有一个按钮来“建造小屋”。基本上,每次按下int值时,将其加1。然后我想在标签上显示建造了多少间小屋。但是label1.Text只接受字符串值

但是,当我转换integer.ToString时,它不起作用。它将数字保持在1,而不增加

public void Button1_Click(object sender, EventArgs e)
{
    int numberofhuts = 0;
    numberofhuts++;
    label1.Text = numberofhuts;
}

这就是它看起来的样子。非常感谢您的帮助。

现在,您每次单击按钮(如其他人所指出的),都会将变量
numberofhuts
重置为零。因此,您需要做以下两件事之一:

  • 将变量移动到更大的范围(即,将其移到按钮单击功能之外)
  • 使用标签文本作为增量的起点
  • 第二种方法可能不是最好的,因为这需要某种机制来确保标签文本始终是数字。所以你可以这样做:

    public partial class MyForm : Form
    {
        // Constructor (normally generated by Visual Studio)
        public MyForm()
        {
            InitializeComponent();
        }
    
        // Create, and initialize the variable outside the method.
        private int _numberOfHuts = 0;
    
        // When clicking the button, the variable is incremented
        // and the label is updated with the new value.
        private void Button1_Click(object sender, EventArgs e) 
        {
            _numberOfHuts++;
            label1.Text = numberOfHuts.ToString();
        }
    }
    
    你也应该考虑一下你的名字。像
    Button1
    Label1
    这样的名称是糟糕的选择,因为它们根本无法表明它们是什么。相反,对按钮使用类似于
    IncrementHutCount
    的内容,对标签使用类似于
    NumberOfHuts
    的内容

    编辑:
    请注意,我所做的范围更改可能不够广泛。我只是假设你只有一个表单,它在程序的整个生命周期内都有效。如果不是这样,您需要将其移动到其他地方

    你有没有学过变量的范围?例如,如果在方法内部声明
    numberofhuts
    ,则每次调用该方法时都会重新创建该变量。如果希望该值保持不变,则需要将其存储在其他位置。顺便问一下,这是什么类型的应用程序?网络表单?赢表格?顺便说一下,正常的C#约定是对局部变量进行camelCase处理,因此应该是
    numberOfHuts
    。它使代码更具可读性,即使您不这样做,使用您的代码的其他开发人员也会欣赏它。每次运行此按钮代码时,它都会做三件事:(1)分配一个点来存储一个数字,(2)增加该数字,(3)将标签文本设置为该数字。如果每次都是1,那么这个数字会发生什么变化?@davedno C#没有全局变量的概念,因此这可能会产生误导。如果你的意思是a,那么请改为说。但是,字段可能无法解决此问题,因为我们不知道该类的生命周期。这就是为什么我在提出这样一种方法之前会犹豫。“我建议你删除你的评论,直到我们有更多的信息。”梅森同意,加上“你的一部分参数”在这种情况下没有意义。方法签名是事件处理程序的签名,不能更改,无论如何也解决不了任何问题。@mason很公平,尽管标题中有Visual Studio Windows应用程序,再加上
    public void Button1\u Click(object sender,EventArgs e)
    强烈建议使用Windows窗体(默认情况下,WPF和UWP使用
    专用无效按钮(对象发送者,路由目标e)
    )。你似乎假设这是Windows窗体…这是一个危险的假设。我会等到问题明确后再用特定的方法回答。@mason你是对的,我应该提到我所做的假设。我已经试图澄清这一点。谢谢。@Noceo如果假设这是WinForms,则
    MyForm
    类s应该从
    表单继承以避免混淆。@Amy你是对的。它也应该是一个分部类。我已经更新了示例。