【发布时间】:2020-12-15 10:31:29
【问题描述】:
我有一个小问题想在脑海中解决。 我有一个整数,我每秒递增一次。我将此整数作为对另一个表单的引用传递并希望显示它。因此,通过单击按钮,我实例化了第二种形式,并将引用指向我第二种形式中的本地整数。
我在第二个表单上每秒显示一次值,但它只会在我重新创建一个新的 form2 实例时更新。
public partial class Form1 : Form
{
private static int test = 0;
public Form1()
{
InitializeComponent();
TestClass.Init();
Timer t = new Timer();
t.Interval = 1000;
t.Tick += new EventHandler(tick);
t.Start();
}
private void tick(object sender, EventArgs e)
{
++test;
}
public delegate void TestEventHandler(ref int test);
public static event TestEventHandler TestEvent;
internal static void TestEventRaised(ref int test)
{
TestEvent?.Invoke(ref test);
}
private void button1_Click(object sender, EventArgs e)
{
TestEventRaised(ref test);
}
}
public static class TestClass
{
private static Form2 form2;
public static void Init()
{
Form1.TestEvent += new Form1.TestEventHandler(Event);
}
private static void Event(ref int test)
{
if (form2 != null)
{
form2.Close();
form2 = null;
}
form2 = new Form2(ref test);
form2.ShowDialog();
}
}
public partial class Form2 : Form
{
int _test = 0;
public Form2(ref int test)
{
InitializeComponent();
_test = test;
Timer t = new Timer();
t.Interval = 1000;
t.Tick += new EventHandler(tick);
t.Start();
}
private void tick(object sender, EventArgs e)
{
label1.Text = _test.ToString();
}
}
我不明白为什么这不起作用,因为当调用 form2 的构造函数时,我将 _test 链接到测试。 TestClass 在我的“真实”代码中有它的目的,即链接作为 DLL 的 Form1 和 Form2。
你知道为什么这不起作用吗?
谢谢!
【问题讨论】:
-
忠告:将数据与演示文稿分开。将该整数和计时器移动到一个单独管理的类中,该类将执行增量或其他操作。你的生活会简单得多。
-
@TanveerBadar 它在我的“真实”代码中。不过,为了简单起见,不在这个问题中添加数百行代码,我将它们全部合并在一起。