1

我需要将一些控件设为静态,例如:

private static System.Windows.Forms.TextBox infoBox;
infoBox = new System.Windows.Forms.TextBox();

所以我将能够在其他课程中使用它:

string myInfo = CourseWork.Form1.infoBox.Text;

但是当我使用视觉设计器时,视觉工作室将我的代码更改为:

private System.Windows.Forms.TextBox infoBox; // it removes static
this.infoBox = new System.Windows.Forms.TextBox(); // and add .this

然后我有下一个错误:

    An object reference is required for the non-static field, 
method, or property 'CourseWork.Form1.infobox'

有可能避免这种情况吗?或者我做错了什么?

4

3 回答 3

2

我认为设计是有缺陷的。infoBox 属于表单,因此表单外的对象不应尝试访问它。

听起来您需要在表单类中添加一个访问器方法,例如GetText(),以便在不违反得墨忒耳定律的情况下为您的其他对象提供可见性。

于 2012-10-15T20:34:58.887 回答
0

If you are sure that there will be at most one instance of the form, you could create a static property exposing the text box's text. In order to do this, you need a static reference to the form itself (I call the form InfoForm, its more informative than Form1).

For this purpose I add a static Open method. If the form is open alredy it brings it to foreground, otherwise it opens it and assigns it to the static field _instance.

public partial class InfoForm : Form
{
    public InfoForm()
    {
        InitializeComponent();
    }

    private static InfoForm _instance;

    public static InfoForm Open()
    {
        if (_instance == null) {
            _instance = new InfoForm();
            _instance.Show();
        } else {
            _instance.BringToFront();
        }
        return _instance;
    }

    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);

        // Make sure _instance is null when form is closed
        _instance = null;
    }

    // Exposes the text of the infoBox
    public static string InfoText
    {
        get { return _instance == null ? null : _instance.infoBox.Text; }
        set { if (_instance != null) _instance.infoBox.Text = value; }
    }
}

Now you can open the form and access its infoText TextBox like this

InfoForm.Open();
InfoForm.InfoText = "Hello";
string msg = InfoForm.InfoText;
于 2012-10-15T21:01:27.437 回答
0

不要......做......它!

使用方法公开控件,我什至建议使用 Invoke 驱动的方法公开控件属性的更改,这样如果更改称为跨线程,它将被正确处理。

例子:

public delegate void SetButtonTextDelegate(string text);
public void SetButtonText(String text)
{
     if(button.InvokeRequired)
     {
         Callback settext = new SetButtonTextDelegate(SetButtonText);
         button.Invoke(settext, text);
     }
     else
     {
         button.Text = text;
     }
}

然后在任何外部类中,只需调用 SetButtonText("new text"); 方法

于 2012-10-15T20:37:27.873 回答