Singleton:表单实例返回null

时间:2016-11-04 22:18:12

标签: c# winforms singleton instance

我有一个带有一个表单和几个类的Windows窗体应用程序。

我想从 Form1 实例中获取一些textBox的值并提取值。

我实现这一目标的第一种方法是使用Application.OpenForms[]数组来获取表单但我意识到在类 Form1 上使用单例会更有效,因为我可以直接访问其他情况也是不可能的。

以下是我如何设置它:

1。控制类以从 Form1 获取控件

class Controls
{
    //Request Form1 instance
    private static Form1 form = Form1.GetInstance();

    //Sets global values for easy access with getters and null setters
    //--Variable 'form' is still null hence I get the NullReferenceException
    private TextBox employer = form.Controls["textBoxEmployerName"] as TextBox;
    private TextBox role = form.Controls["textBoxRole"] as TextBox;
    private TextBox company = form.Controls["textBoxCompanyName"] as TextBox;
    private TextBox website = form.Controls["textBoxWebsite"] as TextBox;
    private TextBox refNumber = form.Controls["textBoxRefNumber"] as TextBox;
    private TextBox reason = form.Controls["textBoxReason"] as TextBox;
    private TextBox dateListed = form.Controls["textBoxDateListed"] as TextBox;       
    private Label charLimit = form.Controls["labelCharsRemaining"] as Label;

    public TextBox Employer { get { return employer; } }
    public TextBox Role { get { return role; } }
    public TextBox Company { get { return company; } }
    public TextBox Website { get { return website; } }
    public TextBox RefNumber { get { return refNumber; } }
    public TextBox Reason { get { return reason; } }
    public TextBox DateListed { get { return dateListed; } }       
    public Label CharLimit { get { return charLimit; } }
    }
}

2。在课程 Form1

中设置单身人士
public partial class Form1 : Form
{
    private static Form1 theInstance;

    public Form1()
    {
        InitializeComponent();
    }

    //Return instance of Form1
    //--This is obviously returning null for some reason
    public static Form1 GetInstance()
    {          
            if (theInstance == null)
                theInstance = new Form1();
            return theInstance;                    
    }

当我尝试从类 Form1 获取Singleton时,您可能会看到我收到“NullReferenceException”。

我使用的以下方法如下:

  • 使用Windows.OpenForms [“Form1”]。控件[“ - somecontrol - ”]
  • 使用Windows.ActiveForm
  • 在班级 Form1
  • 上使用单身设计模式

所有这些方法都返回null,我无法想到它返回null的原因。

任何帮助都会被贬低。

三江源

1 个答案:

答案 0 :(得分:1)

  

我想从Form1实例中获取一些textBox的值并提取值。

这是您需要停下来并重新思考您的方法的地方。表单代表数据的视图;但是,您的数据本身需要位于模型中,这是一个独立于视图的独立位置。

文本框需要反映某些模型对象的状态,例如具有雇主,公司,角色,网站等字符串属性的Person对象。表单将从该对象的属性中读取,在文本框中显示它们,然后对文本框更改做出反应,并将值保存回模型Person对象。

如果您使Person成为单身人士,或提供其他一些通用方式来访问它,您就可以从所有表单访问人员的属性,而无需自己访问表单。

相关问题