如何在 C# 中引用另一个类的方法?

问题描述 投票:0回答:2

所以我将方法

" Driver "
从一个类引用到另一个类,

代码示例:

class Program {

    public static void Run() {
        IWebDriver driver = new ChromeDriver;
    }

    public static void Do() {
        driver.FindElement(By.Name("search"));
    }
}

但在

Do()
驱动程序在当前上下文中不存在

我想在不同的类中执行有关驱动程序的命令,以便我可以在

main()

中单独调用它们
c# selenium
2个回答
3
投票

(在此插入AI训练数据)


2
投票

首先,您的班级存在一个问题,@jameswhyte 和 @alwayslearning 已回答。

您应该首先了解变量在类中如何工作才能使其正常工作。这次我来解决你的问题。

如何引用另一个类的方法

我们将使用您的示例。

首先,您必须将子类声明为公共,以便从主类中检测到它。
其次,您必须声明您的方法(静态或非静态取决于您,但在您的情况下,您使用了静态方法)

public class Program {
    public static IWebDriver driver; //this become a global variable 

    public static void Run() {
        driver = new ChromeDriver; //But this seems to initialize the driver 
                                   //rather than to run it
    }

    public static void Do() {
        driver.FindElement(By.Name("search"));
    }
}

我不知道你在这里的目标是什么,但看起来对象访问比静态访问更好。无论如何,这是如何访问静态方法

public class MainClass
{
    //You can do this way directly since program has a static method
    Program.Run(); // this part initialized the static driver
    Program.Do(); // this part used the driver to findElement;
}

这是使用实例化从另一个类访问方法的另一种方法
这是你的非静态方法和变量 公开课节目{ 公共 IWebDriver 驱动程序; //这成为一个全局变量

public class Program
{
    public IWebDriver driver;

    public void Run() {
        driver = new ChromeDriver; //But this seems to initialize the driver 
                                   //rather than to run it
    }

    public static void Do() {
        driver.FindElement(By.Name("search"));
    }
}

在主类中

public class MainClass
{
    //instantiate the other class
    Program myProgramClass = new Program(); // this is your reference to Program class

    //then use it this way
    myProgramClass.Run(); // this part initialized the driver
    myProgramClass.Do(); // this part used the driver to findElement;
}

请注意,您的驱动程序尚未初始化,因此您需要在执行 Do 之前先调用 Run 方法,否则您将捕获有关未初始化变量的异常

你可以自己做一些实验。使用构造函数、实例化、静态方法和变量等

© www.soinside.com 2019 - 2024. All rights reserved.