只要通过控制
是的;您只需要提供适当类型的参数。例如:
static void UpdateProperties(System.Windows.Forms.Controls.TextBox textbox)
{
textBox.BackColor = Color.White;
textBox.MultiLine = true;
}
然后,在你的主程序中
MyClass.UpdateProperties(PText);
或将控件作为祖先类型传递
您还可以将参数定义为Control,它允许您传递任何控件,而不仅仅是文本框。但是,该函数只能设置所有控件共有的属性(例如Text)。
static void UpdateText(System.Windows.Forms.Controls.Control control)
{
control.Text = "Test";
}
//Main program
MyClass.UpdateText(PControl);
使用扩展方法
你也可以使用extension method语法,像这样:
namespace MyExtensionMethodNamespace
{
public class MyExtensionMethodClass
{
static public void UpdateProperties(this System.Windows.Forms.Controls.TextBox textbox)
{
textBox.BackColor = Color.White;
textBox.MultiLine = true;
}
static public void UpdateText(this System.Windows.Forms.Controls.Control control)
{
control.Text = "Test";
}
}
}
//Main program
using MyExtensionMethodNamespace;
this.PTextBox.UpdateProperties();
this.PTextBox.UpdateText();
使用流畅的语法
如果您编写扩展方法使其返回this,您可以使用流畅的语法,如下所示:
namespace MyExtensionMethodNamespace
{
public class MyExtensionMethodClass
{
static public TextBox UpdateProperties(this TextBox textbox)
{
textBox.BackColor = Color.White;
textBox.MultiLine = true;
return textBox;
}
static public Control UpdateText(this Control control)
{
control.Text = "Test";
return control;
}
}
}
//Main program
using MyExtensionMethodNamespace;
this.PTextBox.UpdateProperties().UpdateText();
这个解决方案很好,因为您可以在一行中完成所有更新。
同时使用多个控件
一旦您弄清楚如何执行上述操作,您就可以对其进行修改以一次使用多个控件,如下所示:
namespace MyExtensionMethodNamespace
{
public class MyExtensionMethodClass
{
static public IEnumerable<TextBox> UpdateProperties(this IEnumerable<TextBox> textboxes)
{
foreach( var textBox in textBoxes)
{
textBox.BackColor = Color.White;
textBox.MultiLine = true;
}
return textBoxes;
}
static public IEnumerable<Control> UpdateText(this IEnumerable<Control> controls)
{
foreach ( var control in controls)
{
control.Text = "Test";
}
return controls;
}
}
}
//Main program
using MyExtensionMethodNamespace;
//Update three specific controls
new [] {myControl1, myControl2, myControl3}.UpdateProperties().UpdateText();
//Update all controls on the form
this.Controls.UpdateProperties().UpdateText();
//Update all TextBox controls on the form
this.Controls.OfType<TextBox>.UpdateProperties().UpdateText();
如果您经常发现自己一次更新多个控件,这会很有帮助。
使用 LINQ
当然,您始终可以使用 LINQ 并传递委托。
using System.Linq;
//Set three specific controls
new[]{myControl1, myControl2, myControl2}.ToList().ForEach(a => {a.Text = "Test"; a.BackColor = Color.Red; a.MultiLine = true});
//Set all controls
this.Controls.ToList().ForEach(a => {a.Text = "Test"; a.BackColor = Color.Red; a.MultiLine = true});
//Set all TextBox controls
this.Controls.OfType<TextBox>.ToList().ForEach(a => {a.Text = "Test"; a.BackColor = Color.Red; a.MultiLine = true});
这个解决方案很好,因为您根本不需要编写任何辅助函数。