尽管是公共的并且在构造函数中定义,但无法访问字段

时间:2019-04-09 13:01:14

标签: c# asp.net webforms

您好,我正在尝试引用表格之间的内容。我得到了他的密码...

main.cs

namespace GDISClient
{
    public class Program : ApplicationContext
    {
        public Form_main mainForm = null;

        public static int startvar = 0;

        private static void Main(string[] args)
        {
            var splash = new Splashscreen(new Form_main());
            Application.Run(splash);
        }
        public Program(Form_main mainForm)
        {
            this.mainForm = mainForm;

        }
    }
} 

splashcreen (form)

namespace GDISClient
{
    public partial class Splashscreen : Form
    {
        public Form_main mainForm;

        public Splashscreen(Form_main mainForm)
        {
            this.mainForm = mainForm;
        }

        private System.ComponentModel.IContainer components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private pwencode encoder = new pwencode();
        private dbcon mysqlcon = new dbcon(mainForm); // <- this here wont work because he can not reference to that, why ?
    }
}

我尝试引用new dbcon(mainForm),但无法访问此mainform,但它是公共的,因此将其移至构造函数中,该怎么办?

2 个答案:

答案 0 :(得分:1)

您的mainForm尚未初始化。在构造函数中创建dbcon,然后在其中传递对mainForm的引用。

答案 1 :(得分:1)

根据我对您问题的理解。问题在这里:

public Form_main mainForm;  // Declared but not Initialized 
private dbcon mysqlcon = new dbcon(mainForm);  // using a variable that has not been initialized

解决方案:constructor的{​​{1}}替换为给定的Splashscreen

constructor