I have a user control and I want the developer who drops the user control on the winform, can tests some values before this user control does something
I want to know if my method is good and if there is a better way to do this ?
Actually in my user control, I have a collection of 开发者_开发知识库List<IValidator>
which is exposed publicly, to the developer could add IValidator
which has implemented. This interface implements only a bool Validate()
method.
The user control have a method named Validate()
which iterate on the List<IValidator>
collection and calls Validate() method.
Here is the code :
public partial class MyUserControl : UserControl
{
private SqlConnection _connection;
private List<IValidator> _validators;
private void button1_Click(object sender, EventArgs e)
{
Validate();
}
private bool Validate()
{
foreach (IValidator validator in this.Validators)
{
validator.Validate();
}
}
public List<IValidator> Validators
{
get { return _customValidators; }
set { _customValidators = value; }
}
}
And the code in the winform hosting the user control :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Validator val1 = new Validator();
myUserControl1.Validators.Add(val1);
}
}
public class Validator : IValidator
{
public bool Validate()
{
return true;
}
}
I would know if there it could be "improved" or "simplified" (without implementing an interface) with the C# 3 syntax (lambda etc.) by the way.
private void button1_Click(object sender, EventArgs e)
{
this.Validators.ForEach(v => v.Validate());
}
or even:
button1.Click += (sender, e) => { this.Validators.ForEach(v => v.Validate()); };
精彩评论