如何在新类中使用Form1中的静态方法

本文关键字:Form1 静态方法 新类中 | 更新日期: 2023-09-27 18:26:30

在Form1的顶部,我在构造函数中添加了一个bool变量,并将其设置为false。然后在按钮点击事件中,我将其设置为true:

private void DriverVerifier_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you Sure you want to Launch the Driver Verifier. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                verifier = false;
            }
            else
            {
                verifier = true;
                verifiers(verifier);
                ProcessRun.Processing(Environment.SystemDirectory, "verifier.exe", "", false, "");
            }
        }

然后在底部我创建了验证器方法:

public static bool verifiers(bool verify)
        {
            return verify;
        }

然后在新的课堂上,我做了:

if (Form1.verifiers(
   System.Threading.Thread.Sleep(500);
   SetForegroundWindow(proc.MainWindowHandle);

但当我在新类中执行Form1.verifiers时,它要求一个bool变量。我想做的只是检查来自form1验证器的方法是真是假。

我现在该怎么办?

如何在新类中使用Form1中的静态方法

verifiers方法需要一个bool参数,因此您必须提供一个:

bool verifier = true;
if (Form1.verifiers(verifier))
{
    System.Threading.Thread.Sleep(500);
    SetForegroundWindow(proc.MainWindowHandle);
}

重写它,使其不接受任何参数或提供无参数过载:

public static bool verifiers()
{
    ...
    return verify;
}
...
if (Form1.verifiers())
{
    System.Threading.Thread.Sleep(500);
    SetForegroundWindow(proc.MainWindowHandle);
}

一件简单的事情。。我们可以通过引用类名来使用静态方法

所以我更喜欢你制作一个新的类,其中你有静态方法Verifier

然后您可以通过Class1.Verifier()从应用程序中调用它

通过将它放在另一个类中,您将获得在不更改Form1类的情况下更改方法行为的优势

我认为这将有助于你把你的方法并以正确的方式使用它。。。

我认为

if (Form1.verifiers(
   System.Threading.Thread.Sleep(500);
   SetForegroundWindow(proc.MainWindowHandle);

本应是:

if (Form1.verifiers())
{
   System.Threading.Thread.Sleep(500);
   SetForegroundWindow(proc.MainWindowHandle);
}

在这种情况下,您需要将静态方法的构造函数更改为:

public static bool verifiers()