仅在函数中运行特定代码

时间:2018-06-11 14:10:11

标签: c#

public static void Order_go(string url, string name) 
{
    // I want to run the line below only once
    var driver = new ChromeDriver(); 

    driver.Url = (url);  
    IWebElement b_login1 = driver.FindElement(By.Id("login"));
    b_login1.SendKeys("aa");
    IWebElement b_pass1 = driver.FindElement(By.Name("managerPw"));
    b_pass1.SendKeys("123");

    // Execute each time when it is called
}

我试过

Boolean once = true;
if (once)
{
    var driver = new ChromeDriver();
    once = false;
}

但是,当我调用此函数时,once的值再次变为true。 如何只运行一次此代码?

var driver = new ChromeDriver();

2 个答案:

答案 0 :(得分:4)

driver成为您班级的static成员。检查null

static ChromeDriver driver;
public static void Order_go(string url, string name) 
{
     if (driver == null) { driver = new ChromeDriver(); }

     driver.Url = (url);  
     IWebElement b_login1 = driver.FindElement(By.Id("login"));
     b_login1.SendKeys("aa");
     IWebElement b_pass1 = driver.FindElement(By.Name("managerPw"));
     b_pass1.SendKeys("123");
     //Execute each time when it is called
}

我会提醒您ChromeDriver可能不是线程安全的。

答案 1 :(得分:1)

我建议在包含的类中全局初始化它(对不起,如果C#中的术语不正确)。

static ChromeDriver driver = new ChromeDriver();

public static void Order_go(string url, string name) 
{
     driver.Url = (url);  
     IWebElement b_login1 = driver.FindElement(By.Id("login"));
     b_login1.SendKeys("aa");
     IWebElement b_pass1 = driver.FindElement(By.Name("managerPw"));
     b_pass1.SendKeys("123");
     //Execute each time when it is called
}