c# - C# reference issue in another form
问题描述
I have a small issue I wanted to clear in my head. I have a integer that I increment every second. I pass this integer as a reference to another form and want to display it. So through a button click I instanciate the second form and point the reference towards a local integer in my second form.
I display the value every second on the second form but it will only update when I recreate a new form2 instance.
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();
}
}
I do not understand why this is not working since when the constructor of form2 is called, I link _test to test. TestClass has its purpose in my "real" code which is to link both Form1 and Form2 that are DLLs.
Do you have any idea why this is not working ?
Thanks !
解决方案
当调用form2的构造函数时,我将_test链接到测试
不,你没有。
Form2 构造函数中的这行代码:
_test = test;
... 将参数的当前值复制test
到该_test
字段。这就是它所做的一切。test
在这种情况下,您的参数是参数这一事实ref
无关紧要,因为您永远不会在构造函数中写入它(也没有在另一个线程中更新该参数,这将是可见的)。
int
我建议您不要使用两个单独的字段,Counter
而是使用一个类:
public class Counter
{
// TODO: Potentially thread safety, or consider making Value publicly read-only
// with an "Increment" method
public int Value { get; set; }
}
然后两者Form1
和Form2
都可以引用同一个Counter
对象,此时该对象内容的更改将从两种形式中都可见。(我还建议为此避免使用静态字段。)
推荐阅读
- python - Python中可以处理因子变量的多层神经网络
- javascript - 按下一个 id Ramda.js 对双向链表进行排序
- mysql - 引用自身时如何将表连接到自身
- java - IBM Domino Java - 优化对特定 Internet 地址的 $(Rooms) 视图的搜索
- c - 尝试将所有制表符更改为一定数量的空格,K&R 练习 1-20
- mysql - 如何使用 JPA 查询获取最后的数据
- linux - 如何使用 GStreamer 和 VAAPi 解决 RAW 流播放问题
- ruby-on-rails - 在 Google Cloud Run 中使用 Sidekiq 的 Rails 作业不起作用
- amazon-web-services - RHat企业服务器7.7 EC2镜像突然关闭80端口
- javascript - reactjs如何恢复到之前的状态?