将类作为参数传递
本文关键字:参数传递 | 更新日期: 2023-09-27 18:03:41
我有一个表单,我做一些验证。当我实例化表单时,我传递一个类作为参数,这样我就可以更新该类的值。
Bussines _bussines = new Bussines ();
public frmUsuario(Bussines b)
{
_bussines = b;
InitializeComponent();
}
实例化表单
frmUsuario fUsuarios = new frmUsuario(this);
fUsuarios.ShowDialog();
所以,我的问题是:根据OOP,可以这样做吗?对我来说,这似乎是一种懒惰的变通方法,但我不知道有什么更简单的选择。有没有更好的选择?
对不起,我的英语不是我的母语。
更简洁、更间接的方法是使用接口。
国际海事组织
- 表单构造函数不应该依赖于参数
- 你的表单应该能够显示没有任何特定的(商业) 根据表单的状态,你的表单应该有一个不错的用户体验。
但正如其他人巧妙地指出的那样,任何事情都可能是正确的,更重要的是不要通过这样的限制为自己将来设置陷阱。
的例子:
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();
}
}
}
答案是否定的,因为。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; } }
}