【问题标题】:How to get a value contained in a class of other form / C# Windows Forms如何获取包含在其他窗体类中的值/C# Windows 窗体
【发布时间】:2020-04-03 21:57:04
【问题描述】:

一段时间以来,我一直在尝试让两种表单相互共享数据。在这种情况下,将数据从表单 2 继承到 1。我尝试了几种方法,这种方法是我设法实现的最好的方法。

问题是它没有完成工作,第二种形式得到的值总是0,肯定是一个小细节,但我真的不知道如何结束。

非常感谢任何帮助的尝试:)

Form1:

using System;
using ...;

namespace Name
{

    public partial class Form1 : Form
    {
        cntr val = new cntr();
    }

    /// omited code that modifies val.count

    public class cntr
    {
        public int count_ = 0;

        public int count
        {
            get
            {
                return count_;
            }
            set
            {
                count_ = value;
            }
        }
    }
}

Form2:

using System;
using ...;

namespace Name
{

    public partial class Form2 : Form
    {
        cntr aye = new cntr();

        public Form2()
        {
            InitializeComponent();
        }

        private async void Read()
        {
            while (true) /// updating the .Text every 5 seconds
            {
                Box2.Text = aye.count;
                await Task.Delay(500); 
            }
        }
    }


}

【问题讨论】:

    标签: c# winforms class inheritance


    【解决方案1】:

    您已将类cntr() 实例化了两次。因此,您有两个对象在它们自己的实例中工作,而不知道另一个对象已经创建。

    您可以通过实例化一个共享类来处理这种情况。在你的主窗体中实例化类cntr(),然后告诉你的第二个类你的实例在哪里。

    namespace Name
    {
    
        public partial class Form1 : Form
        {
            cntr val = new cntr();
    
            // Tell to your second form to use this shared object
            Form2 form2 = new Form2(val);
            form2.Show();
        }
    
        public class cntr { ... }
    
        public partial class Form2 : Form
        {
            private cntr _aye;
    
            public Form2(cntr sharedCntr)
            {
                // Save the shared object as private property
                _aye = sharedCntr;
                InitializeComponent();
            }
    
            private async void Read()
            {
                while (true)
                {
                    Box2.Text = _aye.count.ToString();
                    await Task.Delay(500);
                }
            }
        }
    }
    

    【讨论】:

    • 如果您将Form1中的字段val标记为protected,您甚至不需要将Form2中的字段镜像为_aye字段。您可以从 Form2 中访问它,因为它继承了 Form1。
    • 不,因为 Form2 类不是从 Form1 派生的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多