首页 > 解决方案 > 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 !

标签: c#eventsref

解决方案


当调用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; }
}

然后两者Form1Form2都可以引用同一个Counter 对象,此时该对象内容的更改将从两种形式中都可见。(我还建议为此避免使用静态字段。)


推荐阅读