将类作为参数传递

时间:2016-08-22 20:16:36

标签: c# winforms

我有一个表单,我会做一些验证。当我实例化表单时,我将一个类作为参数传递,然后我可以更新该类的值。

Bussines _bussines = new Bussines ();

public frmUsuario(Bussines b)
{
    _bussines = b;
    InitializeComponent();
}

实例化表单

frmUsuario fUsuarios = new frmUsuario(this);
fUsuarios.ShowDialog();

所以,我的问题是:根据OOP,可以吗?对我来说似乎是懒惰的工作,但我不知道任何更容易的选择。有更好的选择吗?

对不起我的英语,这不是我的母语。

2 个答案:

答案 0 :(得分:2)

更清洁,更间接的方式是使用界面。

IMO

  • 您的表单构造函数不应该依赖于参数
  • 您的表单应该能够在没有任何特定的情况下显示(Businees)
  • 你的表格应根据其状态展示出一个不错的用户体验

但正如其他人巧妙地指出的那样,任何事情都可能是正确的,更多的是通过这样的限制不会在未来设置陷阱。

示例:

using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class Business
    {
    }

    public interface IBusinessHandler
    {
        Business Business { get; set; }
        void Execute();
    }

    public partial class Form1 : Form, IBusinessHandler
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region IBusinessHandler Members

        public Business Business { get; set; }

        public void Execute()
        {
            // check that we can continue
            if (Business == null)
            {
                MessageBox.Show("Business property not set");
                // or whatever else appropriate
                return;
            }

            // do some work on it
            var s = Business.ToString();
            MessageBox.Show("Work done !");
        }

        #endregion
    }

    internal class Demo
    {
        public Demo()
        {
            IBusinessHandler handler = new Form1();
            handler.Business = new Business();
            handler.Execute();
        }
    }
}

答案 1 :(得分:1)

答案是否定的,因为.NET代码需要表单的无参数构造函数。

想想你如何使用OpenFileDialog。您创建一个实例,然后分配属性。同样如此。

{
    Business item=new Business() { Name="Yoko" };
    //
    BusinessForm dlg=new BusinessForm();
    dlg.Business=item;
    if (dlg.ShowDialog()==DialogResult.OK)
    {
        item=dlg.Business;
    }
}

使用表单代码

public class Business
{
    public string Name { get; set; }
    public bool IsOk { get { return !string.IsNullOrEmpty(Name); } }
}

public partial class BusinessForm : Form
{
    Business business;

    public BusinessForm()
    {
        InitializeComponent();
    }

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

        this.business=new Business();
    }

    public Business Business
    {
        get { return business; }
        set { business=value; }
    }
    public bool IsOk { get { return business.IsOk; } }
}
相关问题