多个.cs文件和访问表单

时间:2010-12-20 10:25:42

标签: c# winforms class

我正在尝试用C#编写我的第一个程序而不使用教程。为了确保我从一开始就采用良好的编码实践,我想在不同的.cs文件中创建每个类。但是,当尝试在这样的.cs文件中访问程序的元素时,我遇到了一些麻烦。

例如,我有一个带有Label和Start按钮的Form1.cs。单击开始按钮时,标签中应出现文本。所以:

Form1.cs 中,我有:

namespace TestProgram
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            WriteToLabel message = new WriteToLabel();
            message.WelcomeMessage();
        }
    }
}

在我单独的 WriteToLabel.cs 文件中:

namespace TestProgram
{
    public class WriteToLabel
    {
        public void WelcomeMessage()
        {
            Form1 myForm = new Form1();
            //myForm..  --> myForm doesn't have an 'outputLabel'?
            outputLabel.Text = "Welcome!"; // This returns an error: 'The name outputLabel does not exits in the current context'.
        }
    }
}

'outputLabel'是我给出标签的(Name),这与Form1.Designer.cs中的名称一致。 这两个文件都使用相同的组件,例如'using System';。

但是,从我的WriteToLabel.cs文件中,我似乎无法访问保存程序的表单。我确实成功地在控制台应用程序中创建了不同的.cs文件,这只会增加我的困惑。所以,我有两个问题:

首先,如何从单独文件中的单独类(即非部分类)访问表单? 第二,这是做这件事的好方法,还是创建不同类的多个实例效率不高?

非常欢迎任何想法或想法,

此致

3 个答案:

答案 0 :(得分:2)

您实际上是在实例化Form1实例,而您需要传入对现有实例的引用:

public void WelcomeMessage(Form1 form)
{
    form.outputLabel.Text = "Welcome";
}

您还需要确保outputLabelForm1的公共(或内部)属性/字段,以便您可以相应地设置值。然后调用代码略有不同:

private void startButton_Click(object sender, EventArgs e)
{
    WriteToLabel message = new WriteToLabel();
    message.WelcomeMessage(this);
}

答案 1 :(得分:2)

设计器自动将控件创建为私有字段,因为WriteToLabel类无法访问它。你需要改变它。 另一个好的开始是将类更改为类似的东西:

namespace TestProgram
{
    public class WriteToLabel
    {
        Form1 form;

        public WriteToLabel(Form1 form)
        {
            this.form = form;
        }

        public void WelcomeMessage()
        {
            //Form1 myForm = new Form1();
            //myForm..  --> myForm doesn't have an 'outputLabel'?
            form.outputLabel.Text = "Welcome!";
        }
    }
}

答案 2 :(得分:1)

您需要确保Form1.outputLabel具有公开内部可见性。

如果类要共享大量的状态或私有方法,则只需要LabelWriter类。如果您拥有的是一组在单独对象上设置属性的方法,那么您可以将它作为方法保存在同一个对象上(在本例中为Form1对象):

void startButton_Click(object sender, EventArgs e)
    {
        displayWelcomeMessage();
    }

void displayWelcomeMessage()
    {
       this.outputLabel = "Welcome!";
    }
相关问题