C#-如何将类作为参数传递

C#-如何将类作为参数传递,c#,function,class,parameters,global,C#,Function,Class,Parameters,Global,因此,我编写了一个代码来检查我的表单中是否有任何字段为空。我有多个表单,我必须在其中几个表单中使用此验证检查。我想将其作为全局函数编写,这样我就不必反复编写相同的代码行。但代码中包含对“this”的引用。如何将调用它的form类作为参数,以便使代码全局化。以下是我的代码: // Checks if any field is empty. foreach (Control ctrl in this.Controls) { //

因此,我编写了一个代码来检查我的表单中是否有任何字段为空。我有多个表单,我必须在其中几个表单中使用此验证检查。我想将其作为全局函数编写,这样我就不必反复编写相同的代码行。但代码中包含对“this”的引用。如何将调用它的form类作为参数,以便使代码全局化。以下是我的代码:

        // Checks if any field is empty.
        foreach (Control ctrl in this.Controls)
        {
            // Checking if it is a textbox.
            if (ctrl is TextBox)
            {
                TextBox txtbx = ctrl as TextBox;
                if (txtbx.Text == String.Empty)
                {
                    MessageBox.Show("Please fill all the fields.", "Empty Fields", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtbx.Focus();
                }
            }

            // Checking if it is a combobox.
            else if (ctrl is ComboBox)
            {
                ComboBox cmbbx = ctrl as ComboBox;
                if (cmbbx.Text == String.Empty)
                {
                    MessageBox.Show("Please fill all the fields.", "Empty Fields", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cmbbx.Focus();
                }
            }
        }
要对代码进行哪些更改以使其可以全局使用。例如,要以这种方式调用代码:

ValidateForm(this);

还是有更好的方法

您可以将该代码块移动到接受
表单的单独方法中

public class Helper
{
    public static void Validate(Form form)
    {
        foreach (Control ctrl in form.Controls)
        {
            ...
            ...
        }
    }
}
您还可以使用LINQ一次选择所有空控件,然后关注第一个控件

var invalidControls = form.Controls.Cast<Control>()
                          .Where(c => (c is TextBox || c is ComboBox) && c.Text == string.Empty);

if (invalidControls.Any())
{
    MessageBox.Show("Please fill all the fields", "Empty Fields",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);

    invalidControls.First().Focus();
}
var invalidControls=form.Controls.Cast()
其中(c=>(c是文本框| | c是组合框)&&c.Text==string.Empty);
if(invalidControls.Any())
{
MessageBox.Show(“请填写所有字段”,“空字段”,
MessageBoxButtons.OK,MessageBoxIcon.Warning);
invalidControls.First().Focus();
}

您可能希望一次检查所有无效字段的指示,这样用户就不会潜在地修复一个字段,而只是在以下每个字段上一次获得一条相同的消息。

是的,您可以执行ValidateForm(这);但是ValidateForm应该声明为ad ValidateForm(Form Form),然后将所有“this”更改为“Form”@Malin谢谢你的帮助,伙计,我找到了解决方案……这种方法应该是静态的。