不能在另一种方法中使用字符串

时间:2018-05-27 07:55:31

标签: c# .net

private void Button_Click(object sender, RoutedEventArgs e)
{
    IWebDriver driver = new ChromeDriver
    {
        Url = filename
    };
    driver.Manage().Window.Maximize();
    Watcher_Changed(driver);
}

private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
    driver.navigate().refresh(); // Can not use driver
}

我尝试在使用上述代码的其他方法中使用driver,但它不起作用,我该怎么做才能使它工作?

3 个答案:

答案 0 :(得分:2)

您在方法中创建driver作为局部变量,这只能在此方法中访问。为了更精确一点,它实际上在scope中可见,你应该在那里阅读。

要使driver可以访问所有函数,您应该传递它,或者在您的方法所在的类中更好地创建它。

答案 1 :(得分:1)

您可以使用sender。像这样:

private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
    var driver = sender as IWebDriver;//Or sender as ChromeDriver
    driver.navigate().refresh(); 
}

然而,您需要将FileSystemEventArgs指定为第二个参数。例如:

Watcher_Changed(driver , null);

答案 2 :(得分:-3)

    I'm not sure but you can try using this
       1)define driver in global scope

    what you are doing is defining and declaring **driver** variable inside the 
     scope of button click.so,it will not be accessible from any other method...

     secondly,if you are making a function call within the button click event 
      then use its function parameters.
      Like in watcher_changed method you can try using this

> assuming you are calling watcher_changed function as watcher_changed(driver,"")
else it will give you error


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

    namespace MyStuff
    {
        public class MyClass : Page
        {
            **`define your IwebDriver here`**

           public void MyButton_Click(Object sender, EventArgs e)
           {
               **access IwebDriver here**
           }

           private void Watcher_Changed(object sender, FileSystemEventArgs e)
           {
               sender.navigate().refresh(); // Can not use driver
           }

       }
    }