[英]How do i reference a method from another class in C#?
因此,我將" Driver "
方法從一個類引用到另一個類,
代碼示例:
class Program {
public static void Run() {
IWebDriver driver = new ChromeDriver;
}
public static void Do() {
driver.FindElement(By.Name("search"));
}
}
但在Do()
驅動程序中,當前上下文中不存在
我想在單獨的類中執行有關驅動程序的命令,以便可以在main()
單獨調用它們
這是代碼范圍的問題。 至少在您提出的代碼中,您將需要執行以下操作。
class Program {
public static IWebDriver driver;
public static void Run() {
driver = new ChromeDriver;
}
public static void Do() {
driver.FindElement(By.Name("search"));
}
}
盡管在您的問題的措辭中,聽起來好像您是在混淆類和函數。
要共享功能,它需要遵守Class或Namespace的范圍。 要與其他類共享值,您必須以可變格式或類似的方式傳入該類的實例。
首先,@ jameswhyte和@alwayslearning回答了您班上的一個問題。
您應該首先了解變量在類中的工作方式,以使其正常工作。 這次,我將解決您的問題。
如何從另一個類引用方法
我們將使用您的示例。
首先,您必須將您的子類聲明為public才能從主類中進行檢測。
其次,您必須聲明您的方法(取決於您自己是靜態還是非靜態,但在您情況下,您使用的是靜態方法)
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;
}
這是使用實例化從另一個類訪問方法的另一種方法
這是您的非靜態方法和變量public class Program {public IWebDriver driver; //這成為一個全局變量
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"));
}
}
在MainClass中
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方法,否則您將捕獲到有關未初始化變量的異常
您可以自己做一些實驗。 使用構造函數,實例化,靜態方法和變量等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.