简体   繁体   English

C#-如何通过类作为参数

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

So I wrote a code to check if there is any field empty in the my form.I have multiple forms and I have to use this validation check in several of them.I wanted to write it as a global function so I don't have to write the same lines of code again and again.But the code contains the reference to "this".How to take form class that is calling it as parameter so I can make the code global.Here is my code: 所以我写了一个代码来检查我的表单中是否有空字段。我有多个表单,我必须在其中几个表单中使用此验证检查。我想将其编写为全局函数,所以我没有一次又一次地写相同的代码行。但是代码中包含对“ this”的引用。如何使用将其调用为参数的表单类,以便使代码成为全局代码。这是我的代码:

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

What changes is to be made to code so it can be used globally.For Example so that it can be called this way: 要对代码进行哪些更改,以便可以全局使用。例如,可以这样调用它:

ValidateForm(this);

Or is there is better way to do it? 还是有更好的方法呢?

You can move that block of code into a separate method that accepts a Form : 您可以将该代码块移到一个接受Form的单独方法中:

public class Helper
{
    public static void Validate(Form form)
    {
        foreach (Control ctrl in form.Controls)
        {
            ...
            ...
        }
    }
}

You could also select all the empty controls at once using LINQ, then focus on the first one. 您也可以使用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();
}

You might want to look into indicating the invalid fields all at once, so the user doesn't potentially fix one, just to get the same message on each of the following ones, one at a time. 您可能希望一次查看所有无效字段,因此用户可能不会修复一个无效字段,而只是想在以下每个字段上都得到相同的消息,一次一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM