C#使用不同形式的类中的类

时间:2016-03-05 08:01:58

标签: c# forms class

我刚开始使用C#和一个Windows窗体应用程序。我也是OOP的新手。我试图创建一个应用程序,用户可以从打开第二个表单的meny修改一些设置。我找到了一种方法,使用额外的“设置类”将用户输入数据从“设置表单”移动到主表单。我不确定我是否以良好的方式做这件事并且正在寻求最佳实践的建议。

我的“主要表单”代码如下:

cout << static_cast<int>(*x) << endl;

“设置表单”的代码如下所示:

namespace Scheduler
{
    public partial class FormScheduler : Form
    {

        public FormScheduler()
        {
            InitializeComponent();
        }

        private PeriodSettings mPeriodSettings = new PeriodSettings();

        public string StartDate
        {
            get{ return mPeriodSettings.StartDate; }

            set{ mPeriodSettings.StartDate = value; }
        }

        private void settingsSchPer_Click(object sender, EventArgs e)
        {
            FormSchemaPeriodSettings formSchPer = new FormSchemaPeriodSettings();
            formSchPer.formScheduler = this;
            formSchPer.Show();
        }

    }
}

例如,我必须在“主窗体”中定义SetDate的正确性,即

部分
namespace Scheduler
{
    public partial class FormSchemaPeriodSettings : Form
    {

        public FormSchemaPeriodSettings()
        {
            InitializeComponent();
        }

        public FormScheduler formScheduler = new FormScheduler();

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            this.formScheduler.StartDate = this.startDate.Value.ToShortDateString();
            this.Close();
        }
    }
}

为了能够访问PeriodSettings类的StartDate,还是有办法能够直接访问已定义的mPeriodSettings.StartDate?

我的PeriodSettings类看起来像:

public string StartDate
{
    get{ return mPeriodSettings.StartDate; }

    set{ mPeriodSettings.StartDate = value; }
}

感谢任何建议!

1 个答案:

答案 0 :(得分:1)

您还可以将设置表单作为对话框打开,并使用DialogResult属性,如下所示:

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

    public string StartDate
    {
        get { return mPeriodSettings.StartDate; }
        set { mPeriodSettings.StartDate = value; }
    }

    private void settingsSchPer_Click(object sender, EventArgs e)
    {
        FormSchemaPeriodSettings formSchPer = new FormSchemaPeriodSettings();
        if (formSchPer.ShowDialog() == DialogResult.OK)
            StartDate = formSchPer.ResultDate;
    }
}

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

    public string ResultDate;

    private void buttonCancel_Click(object sender, EventArgs e)
    {
        Close();
    }

    private void buttonOK_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.OK;
        ResultDate = startDate.ValueToShortDateString();
        Close();
    }
}