另一种形式的C#参考问题

问题描述

我想解决一个小问题。 我有一个整数,每秒递增。我将此整数作为对另一种形式的引用,并希望显示它。因此,通过单击按钮,我实例化第二种形式,并将引用指向第二种形式的局部整数。

我每秒在第二个表单上显示该值,但是只有在我重新创建一个新的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链接到test。 在我的“真实”代码中,TestClass的目的是链接作为DLL的Form1和Form2。

您知道为什么这不起作用吗?

谢谢!

解决方法

当调用form2的构造函数时,我将_test链接到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; }
}

然后Form1Form2都可以引用相同的Counter 对象,这时 content 从这两种形式都可以看到该对象的>。 (我也建议您避免使用静态字段。)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...