c# – 更改时自动更新全局变量中的标签
发布时间:2020-12-15 05:37:06 所属栏目:百科 来源:网络整理
导读:所以这是我的计划. using System;using System.Windows.Forms;namespace WindowsFormsApplication1{ public partial class Form1 : Form { static int count = 0; public Form1(){InitializeComponent();} private void button1_Click(object sender,EventAr
所以这是我的计划.
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { static int count = 0; public Form1(){InitializeComponent();} private void button1_Click(object sender,EventArgs e) { count += 1; label1.Text = Convert.ToString(count); } private void button2_Click(object sender,EventArgs e) { count -= 1; label1.Text = Convert.ToString(count); } } } 现在……每当我们按下两个按钮之一并将值保存到全局变量计数然后将其显示在label1中时,我有一个程序可以加1或减1. 假设我想更改另一个标签(label2)的值,我想在每次label1更改时显示count变量值的内容. 所以有一种方法,使用按钮中的事件,可以这样做: private void button1_Click(object sender,EventArgs e) { count += 1; label1.Text = Convert.ToString(count); label2.Text = Convert.ToString(count); } private void button2_Click(object sender,EventArgs e) { count -= 1; label1.Text = Convert.ToString(count); label2.Text = Convert.ToString(count); } 所以这是问题…… 但是让我说我??想更新label2的值而不是从按钮的事件更新,但不知何故,它会在计数变量发生变化时自动更新值. 请帮忙. 解决方法
在这种情况下使用属性
private int count private int Count { get { return count; } set { count = value; RefreshLabels(); } } private void RefreshLabels() { label1.Text = Convert.ToString(count); label2.Text = Convert.ToString(count); } 当你想改变数量时,只需使用属性 Count += 1; Count -= 1; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |