하나의 양식과 몇 개의 클래스가있는 windows Forms 응용 프로그램이 있습니다.싱글 톤 : null을 반환하는 폼 인스턴스
Form1 인스턴스에서 일부 textBoxes의 값을 가져 와서 값을 추출하고 싶습니다.
이 달성의 내 첫 번째 방법은 양식을 얻을 수 Application.OpenForms[]
배열을 사용하여했지만 내가 직접 액세스 할 수 있으며 다른 만들 불가능할 것 같은 클래스 Form1에에 싱글 톤을 사용하는 것이 더 효율적이 될 것이라고 실현 인스턴스.
1 컨트롤 클래스 에서 컨트롤을 얻는다에를 Form1에
싱글이 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 : 여기
내가 그것을 설정 한 방법입니다
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;
}
아마도 알 수 있듯이 클래스에서 Singleton을 얻으려고하면 "NullReferenceException"이 발생합니다 Form1. 다음과 같이
내가 사용한 다음 방법
은 다음과 같습니다 Windows.OpenForms [ "Form1을"] 사용- 제어 [ "- somecontrol--"] Windows.ActiveForm
- 사용
- . 클래스 Form1에
다음과 같은 방법으로 모두에 싱글 톤 디자인 패턴을 사용하여이 null 반환하고 나는 그것이 null이 반환 이유를 생각하지 못할.
도움이 필요합니다.
감사합니다
'form'이 (가) null입니까? 'as' 연산자는 캐스트가 작동하지 않으면 null을 반환하고, form.Controls [ "nonExistentasdf323"]'는 또한'null'을 반환합니다. – Quantic