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

C# - How to make pass a class as an parameter

所以我写了一个代码来检查我的 form.I 有多个表单中是否有任何字段为空,我必须在几个 them.I 中使用此验证检查想把它写成一个全局函数,因此我不必再次编写相同的代码行并且 again.But 代码包含对 "this" 的引用。如何采用将其作为参数调用的形式 class所以我可以让代码 global.Here 是我的代码:

        // 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();
                }
            }
        }

要对代码进行哪些更改才能使用globally.For示例以便可以这样调用:

ValidateForm(this);

或者有更好的方法吗?

您可以将该代码块移动到接受 Form:

的单独方法中
public class Helper
{
    public static void Validate(Form form)
    {
        foreach (Control ctrl in form.Controls)
        {
            ...
            ...
        }
    }
}

您也可以使用 LINQ 一次 select 所有空控件,然后专注于第一个。

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();
}

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