沟通表单的最佳实践是什么?
当我需要将一些信息从一个表单传递到另一个表单时,我通常会执行以下操作:
Form2 form = new Form2(this);
form.ShowDialog();
在 Form2.cs 中,我使用如下构造函数:
private Form1 parent;
public Form2(Form1 form)
{
...
parent = form;
}
这样,仅当 textbox1 为不是 Form1 中的私人成员。好的,很多时候我需要获取 Form1 中控件的信息,我是否应该为 Form2 中所需的控件的每个属性创建 setter 和 getter?例如:我需要知道 Text、ReadOnly 和 Location 的值。我应该为这些属性中的每一个设置 setter 和 getter 吗?使用内部修饰符是一种不好的做法吗?
When I need to pass some information from a form to another I usually do the following:
Form2 form = new Form2(this);
form.ShowDialog();
And inside Form2.cs, I use a constructor like:
private Form1 parent;
public Form2(Form1 form)
{
...
parent = form;
}
This way I can get a information from a textbox doing parent.textbox1.Text only if textbox1 is not a private member from Form1. Ok, a lot of time I need to get information about controls in Form1, should I make the setters and getters for each attribute of a control needed in Form2? For example: I need to know the values of Text, ReadOnly and Location. Should I make the setters and getters for each one of these attributes? Is the use of internal modifier a bad practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正确的做法是与代表一起。它们确实非常简单,但需要一些时间才能理解它们。这是我认为您正在寻找的一个很好的例子: http://samgaut.blogspot.com/2007/11/use-delegates-to-pass-data- Between.html
The correct way to do it is with delegates. They are really pretty simple but it takes awhile to get your head around them. Here is a great example of what I think you're looking for: http://samgaut.blogspot.com/2007/11/use-delegates-to-pass-data-between.html
由于不允许我对答案添加评论,因此我将添加此内容。
已接受答案中的链接博客文章对我来说没有意义(可能只是我对代表缺乏透彻的了解)。
如果下一个内嵌表单
frmDestination
有一个可公开访问的 setter 方法 (SetCustomerID(string strCustID)
),那么当您可以直接将customerID
传递给 setter 吗?我注意到他提到了这一点
在
dest.Show()
之前调用dest.SetCustomerID(customerID)
不会做同样的事情吗?Since I am not allowed to add comments to answers I'm going to add this.
The linked blog post from the accepted answer does not make sense to me (could just be my lack of thorough understanding of delegates).
If the next-in-line form
frmDestination
has a publicly accessible setter method (SetCustomerID(string strCustID)
), then why do you need to pass that into a delegate when you can just passcustomerID
directly to the setter?I noticed he mentioned that
Would just calling
dest.SetCustomerID(customerID)
beforedest.Show()
not do the same thing?据我所知,这不是一个可重用的框架,因此我不会围绕控件属性创建包装器属性。
如果此父窗体需要灵活一些,那么正确的做法可能是使用指定特定控件存在的接口或特定的基窗体类。
Seeing as this is not a reusable framework from what I can tell, I wouldn't create wrapper properties around the control properties.
If there was something that needed to be flexible about this parent form then the proper course might be to use an interface that specifies the particular controls exist or a specific base form class.